How to indexing directly multiple row?
4 views (last 30 days)
Show older comments
Dear all, I wonder how we can do direct indexing in compact form, for the following case? In this problem, i want to extract two rows for different columns. To achieve the objective, the following code was realize. But, the code is lengthy, and I wonder if we can simplify this.
Thanks in advance.
ShufleNperc=5;
randm_row_NUm=[randperm(ShufleNperc);randperm(ShufleNperc)]; % Row idx
randm_no=randi(50,ShufleNperc,ShufleNperc); % value to be extracted base on the row
vvvv=zeros(size(randm_row_NUm,1),ShufleNperc); % Prelocate memory
for x_v=1:ShufleNperc
vvvv(:,x_v)=randm_no((randm_row_NUm(:,x_v))',x_v);
end
0 Comments
Accepted Answer
KL
on 4 Dec 2017
Edited: KL
on 4 Dec 2017
use linear indices,
With your example,
colInd = repmat(1:size(randm_no,2),2,1);
linind = sub2ind(size(randm_no),randm_row_NUm(:),colInd(:));
vvvv_simple = randm_no(linind);
you can reshape it if you want,
vvvv_simple = reshape(vvvv_simple,size(vvvv))
the result is the same for both methods,
>> vvvv
vvvv =
48 48 33 38 3
8 22 43 33 5
>> vvvv_simple
vvvv_simple =
48 48 33 38 3
8 22 43 33 5
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!