Lucas Tesch
Lucas Tesch

Reputation: 157

Finding coordinates min and max of a matrix without using min/max commands

I have this code that shows me min and max values from a random matrix without using min/max commands:

   m = rand(5,5)*10
    mn = m(1);
    mx = m(1);
    for ii = 2:numel(m)
        if m(ii) < mn
            mn = m(ii);
            imn = ii;
        elseif m(ii) > mx
            mx = m(ii);
            imx = ii;
        end
    end
    disp(mx)
    disp(mn)

How can I also find the minimum and maximum coordinate/position? I need to do this only with the function for, or loop, and i'm using matlab version 2018a

Upvotes: 0

Views: 266

Answers (2)

PhoenixBlue
PhoenixBlue

Reputation: 1037

A = rand(5,5);
B = A(:);
[B,I] = sort(B);
m_min = B(1);
m_max = B(end);
index_min = I(1);
index_max = I(end);
  • Generate the random array
  • Convert the array into a vector
  • Sort the vector
  • Maximum is the last item
  • Minimum is the first item

I have modified the code to show indices of extrema. The equivalent indices as coordinates in the array can be found using ind2subs

coord_max = ind2subs([5,5], index_max);
coord_min = ind2subs([5,5], index_min);

Upvotes: 2

Dev-iL
Dev-iL

Reputation: 24159

You can do this with sorting:

function [minVal, maxVal, cMin, cMax] = q52961181(m)
if ~nargin, m = rand(5,5); end
sz = size(m);
[v,c] = sort(m(:), 'ascend');
% at this point, the *linear* indices of the minimum and the maximum are c(1) and c(end),
% respectively.
[x,y] = ind2sub(sz, c([1,end]));
assert(isequal(numel(x), numel(y), 2)); % make sure we don't have repetitions
minVal = v(1); maxVal = v(2);
cMin = [x(1), y(1)];
cMax = [x(2), y(2)];

Or using find:

function [minVal, maxVal, cMin, cMax] = q52961181(m)
if ~nargin, m = rand(5,5); end
[minVal,maxVal] = bounds(m,'all'); % "bounds" was introduced in R2017a
[cMin, cMax] = deal(zeros(1,2));
[cMin(1), cMin(2)] = find(m == minVal);
[cMax(1), cMax(2)] = find(m == maxVal);

(This solution is technically cheating, since bounds calls min and max internally. However, you can just use your own code instead to determine the minimum and maximum values.)

Upvotes: 0

Related Questions