Index a Y = MxN, with X=Mx5 (where elements in X are column IDs for values to extract from Y)
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2023-12-6
编辑:Voss
2023-12-6
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 个评论
Voss
2023-12-6
编辑:Voss
2023-12-6
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)
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!