Index a Y = MxN, with X=Mx5 (where elements in X are column IDs for values to extract from Y)
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Voss
am 6 Dez. 2023
Bearbeitet: Voss
am 6 Dez. 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 Kommentare
Voss
am 6 Dez. 2023
Bearbeitet: Voss
am 6 Dez. 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)
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!