How to index this matrix ?
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (3)
Image Analyst
on 6 Dec 2018
Maybe try
minValue = min(X(:));
linearIndexes = find(X(:) == minValue);
then use ind2sub(size(X), linearIndex) to get the sets of 5 indexes.
2 Comments
Stephen23
on 6 Dec 2018
Edited: Stephen23
on 6 Dec 2018
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)
0 Comments
Abdallah
on 1 Feb 2023
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
0 Comments
See Also
Categories
Find more on Number Theory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!