How to index this matrix ?

Hi all,
I have a problem while indexing a matrix with the result of the "min" function. My problem can be resumed as this :
B is a 5D matrix. (size = [ 2 2 3 3 240])
I have to know the position of the minimums of B accoarding to the 5th dimension.
Knowinw the position of this minimum, I want to transform M, another matrix with the same size (5D), into a 4D matrix keeping the values of the 5th dimension corresponding to the minimum values of B.
Now, I use this :
[U,Xm] = min(B,[],5)
Xm is a 4D matrix as expected.
The problems is that Xm values are the index in the dim.6, and not the indexing of the matrix. So I can not use : M(Xm).
Do you have an idea for that ?
Thank you a lot

Réponses (3)

Image Analyst
Image Analyst le 6 Déc 2018

0 votes

Maybe try
minValue = min(X(:));
linearIndexes = find(X(:) == minValue);
then use ind2sub(size(X), linearIndex) to get the sets of 5 indexes.

2 commentaires

Like this ?
vals = min(B,[],5);
linearIndexes = find(B == vals);
[a1,a2,a3,a4,a5] = ind2sub(size(B), linearIndexes);
The problem is that I get this size for a1,a2... :
size(a1) = 234 1
So I can not get the right values inside M using something like :
M(a1,a2,a3,a4)
Because I want M to be the size :
size = [ 2 2 3 3 1]
Do you know how to have the result with the right size ?
Image Analyst
Image Analyst le 6 Déc 2018
How many locations does the max appear in?
Attach B in a .mat file.

Connectez-vous pour commenter.

Stephen23
Stephen23 le 6 Déc 2018
Modifié(e) : Stephen23 le 6 Déc 2018

0 votes

Several years ago I wrote an efficient function that returned the linear indices corresponding to any ND indices returned by min or max. But there was a resounding lack of interest from other users of FEX, so I deleted it again.
The straightforward way (but not the fastest) is to generate all of the subscript indices yourself, substitute the ones returned by min / max and then use those to generate an array of linear indices:
szb = size(B);
szx = size(Xm);
szx(end+1:numel(szb)) = 1;
tmp = arrayfun(@(n)1:n,szx,'uni',0);
[tmp{:}] = ndgrid(tmp{:});
tmp{szx~=szb} = Xm;
idx = sub2ind(szb,tmp{:});
And then all you need is:
M(idx)
Abdallah
Abdallah le 1 Fév 2023

0 votes

I know it's too late but might help someone else
Use five for loops as follows:
B_min=min(B)
for i=1:2
for j=1:2
for u=1:3
for v=1:3
for w=1:240
if B(i,j,u,v,w)==B_min
ii=i;
jj=j;
uu=u;
vv=v;
ww=w;
end
end
end
end
end
end

Catégories

En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange

Produits

Version

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by