Index a Y = MxN, with X=Mx5 (where elements in X are column IDs for values to extract from Y)
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Voss
il 6 Dic 2023
Modificato: Voss
il 6 Dic 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 Commenti
Voss
il 6 Dic 2023
Modificato: Voss
il 6 Dic 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)
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!