Index a Y = MxN, with X=Mx5 (where elements in X are column IDs for values to extract from Y)
2 views (last 30 days)
Show older comments
Having a Y = MxN matrix of data, and a X = Mx5 (or other fixed nr. < than N) matrix obtained as:
[~, X] = maxk(Z,5,2); % where Z has the same size as Y
is there a non-FOR way to extract the values from Y coresponding to positions as expressed in X? Current solution is:
for line = 1:size(Y,1)
X1(line,:) = Y(line, X(line,:))
end
0 Comments
Accepted Answer
Voss
on 6 Dec 2023
Edited: Voss
on 6 Dec 2023
You can use sub2ind for that.
Example:
Y = randi(50,6,10)
Z = Y/100;
[~,X] = maxk(Z,5,2)
% non for-loop method:
[M,N] = size(Y);
rows = repmat((1:M).',1,size(X,2));
cols = X;
X1 = Y(sub2ind([M N],rows,cols))
% for-loop method:
X1_for = zeros(size(Y,1),size(X,2));
for line = 1:size(Y,1)
X1_for(line,:) = Y(line, X(line,:));
end
X1_for
% both methods produce the same result:
isequal(X1,X1_for)
2 Comments
Voss
on 6 Dec 2023
Edited: Voss
on 6 Dec 2023
Y = randi(50,6,10)
Z = Y/100;
[~,X] = maxk(Z,5,2)
% one-liner:
X1 = Y((X-1)*size(Y,1)+(1:size(Y,1)).')
% for-loop method:
X1_for = zeros(size(Y,1),size(X,2));
for line = 1:size(Y,1)
X1_for(line,:) = Y(line, X(line,:));
end
X1_for
% both methods produce the same result:
isequal(X1,X1_for)
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!