-5

I have written the following 'matlab' code that is supposed to return the maximum value in an array:

function m = maxi(a)
maximum = a(1,1);
[m,n]=size(a);
for i=1:m
    for j=1:n
        if a(i,j)>=maximum
            maximum = a(i,j)
        else
            maximum = maximum;
        end
    end
end
m = maximum;
end

The case here is that the returned result seems to be the maximum number in each iteration. How can I return only one value, which is the maximum value?

Thanks.

Simplicity
  • 47,404
  • 98
  • 256
  • 385
  • 1
    why not use the builtin function `max()`? – Fredrik Pihl Apr 04 '13 at 14:03
  • 2
    You are using `m` both as the number of rows and for the maximal element - this is **not** a good practice. – Shai Apr 04 '13 at 14:05
  • Furthermore, [it is best not to use `i` and `j` as variable names in matlab](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab). – Shai Apr 04 '13 at 14:06
  • @Fredrik Pihl. I faced the same issue when using the built in `max` function – Simplicity Apr 04 '13 at 14:10
  • @Shai: for those of us who work with real numbers only, it's not so bad to use i and j. There can be a trade-off between being able to handle imaginary numbers and being to easily proof-read complicated formulas. – Jonas Apr 04 '13 at 14:20

1 Answers1

7

To find the maximum value in an array, it is advisable to use the built-in function max. Note that max operates along the first dimension of the array by default; to find the overall max, you may therefore want to pass your array as a vector:

overallMax = max(array(:));

Really, it's not recommended to re-implement built-ins if performance is at all important. However, for educational purposes, it can be useful to reverse-engineer code.

Your function runs fine for me, though I would suggest that you iterate over linear indices (similar to how you transform the array to a vector above). This way it will work for an array of arbitrary dimensionality.

function mx = maxi(a)
  mx = a(1);
  for ii = 1:numel(a)
      if a(ii) > mx
         mx = a(ii);
      end
  end
Jonas
  • 74,690
  • 10
  • 137
  • 177