ob269
ob269

Reputation: 13

Matlab matrix minimum value

I have a a matrix Number which contains

0.2728    0.2304    0.2008    0.1900    0.2008    0.2304    0.2728
0.2304    0.1786    0.1391    0.1233    0.1391    0.1786    0.2304
0.2008    0.1391    0.0843    0.0567    0.0843    0.1391    0.2008
0.1900    0.1233    0.0567    0.0100    0.0567    0.1233    0.1900
0.2008    0.1391    0.0843    0.0567    0.0843    0.1391    0.2008
0.2304    0.1786    0.1391    0.1233    0.1391    0.1786    0.2304
0.2728    0.2304    0.2008    0.1900    0.2008    0.2304    0.2728

I am trying to find the minimum value (or values if there are equal mins). I have tried

[min_val,idx]=min(number);

[row,col]=ind2sub(size(number),idx);

I am getting row 4 which is right but col 1 which clearly not the min, min is in the center. When I print min(number) I am give the whole of row 4 so I also tried

[min_val,idx]=min(min(number));

[row,col]=ind2sub(size(number),idx);

But i's giving the same result. I'm not really sure what's going on here. Any help would be appreciated!

Code used to get the positions of multiple minimums.

[min_val, idx] = min(number(:));%finds minimum value of n
mins = number==min_val;%logical array that gives 1 where number is at 
its minimum

ind1 = zeros();
ind2= zeros();
for i = 1:length(x)
    for j = 1:length(y)
        if min_val(i,j) == 1
            ind1 = [ind1;i];% indcies where mins = 1 
            ind2 = [ind2;j];
        
        end
    end
end
ind1 = ind1(ind1~=0);

Upvotes: 1

Views: 490

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22472

Looks like you can use min and ind2sub to achieve your expected output:

matlab:1> number = [0.2728 0.2304 0.2008 0.1900 0.2008 0.2304 0.2728; 0.2304 0.1786 0.1391 0.1233 0.1391 0.1786 0.2304; 0.2008 0.1391 0.0843 0.0567 0.0843 0.1391 0.2008; 0.1900 0.1233 0.0567 0.0100 0.0567 0.1233 0.1900; 0.2008 0.1391 0.0843 0.0567 0.0843 0.1391 0.2008; 0.2304 0.1786 0.1391 0.1233 0.1391 0.1786 0.2304; 0.2728 0.2304 0.2008 0.1900 0.2008 0.2304 0.2728]
number =

   0.272800   0.230400   0.200800   0.190000   0.200800   0.230400   0.272800
   0.230400   0.178600   0.139100   0.123300   0.139100   0.178600   0.230400
   0.200800   0.139100   0.084300   0.056700   0.084300   0.139100   0.200800
   0.190000   0.123300   0.056700   0.010000   0.056700   0.123300   0.190000
   0.200800   0.139100   0.084300   0.056700   0.084300   0.139100   0.200800
   0.230400   0.178600   0.139100   0.123300   0.139100   0.178600   0.230400
   0.272800   0.230400   0.200800   0.190000   0.200800   0.230400   0.272800

matlab:2> [min_val, idx] = min(number(:))
min_val = 0.010000
idx = 25
matlab:3> [row, col] = ind2sub(size(number), idx)
row = 4
col = 4

Upvotes: 0

Related Questions