Find the elements of a ND matrix given the index of the elements

1 vue (au cours des 30 derniers jours)
Asif Newaz
Asif Newaz le 29 Avr 2020
Commenté : Asif Newaz le 29 Avr 2020
[b,idx]=min(a,[],2) -- gives the value as well as the index of the min value of each row of matrix a.
Now the ques is - how to get b if i've 'a' & 'idx'.
For 2D,i can use a for loop to do it.
But how to do it for ND scenarios?
For example,
a=[0.8147 0.9134 0.2785
0.9058 0.6324 0.5469
0.1270 0.0975 0.9575]
b=[0.2785
0.5469
0.0975]
idx=[3
3
2]
for i=1:length(idx)
b(i)=a(i,idx(i));
end
-- it'll do for 2D.
  2 commentaires
darova
darova le 29 Avr 2020
Can you show you calculate idx for 3d dimension?
Asif Newaz
Asif Newaz le 29 Avr 2020
sorry.i dont understand ur question.
For a 3D matrix a,
[b,idx]=min(a,[],2) -will generate a 3D array of idx.

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 29 Avr 2020
Modifié(e) : Stephen23 le 29 Avr 2020
Surprisingly there is no trivial way to do this, but one general solution is to generate linear indices, e.g.:
% input data (any ND array and the corresponding output index from MIN or MAX):
a = [0.8147,0.9134,0.2785;0.9058,0.6324,0.5469;0.1270,0.0975,0.9575]; % ND array.
idx = [3;3;2] % indices, must be the same orientation as returned by MIN or MAX.
% sizes of input data:
idx = double(idx);
sza = size(a);
szn = size(idx);
szn(end+1:numel(sza)) = 1;
idd = szn~=sza;
% linear indices:
tmp = arrayfun(@(n)1:n,szn,'uni',0);
[tmp{:}] = ndgrid(tmp{:});
tmp{idd} = idx;
ndx = sub2ind(sza,tmp{:});
You can use the linear indices very simply:
>> a(ndx)
ans =
0.2785
0.5469
0.0975

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by