Index a Y = MxN, with X=Mx5 (where elements in X are column IDs for values to extract from Y)
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Voss
le 6 Déc 2023
Modifié(e) : Voss
le 6 Déc 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 commentaires
Voss
le 6 Déc 2023
Modifié(e) : Voss
le 6 Déc 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)
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!