Find the largest number in a matrix

Express what a computer is doing in English: The computer performs the following operations numerous times:

  1. Looks at the next number in sequence and calls it current.
  2. Compares the value of current with the value of a variable called help.
  3. Replaces help's value with that of current if it is less.
The computer also initializes some variables. Namely, the computer sets an initial value for help and current.

A concise English description of the actions taken by the computer might look like this:

   1.  Input a matrix of numbers.
   2.  Let current hold the <1,1> number in the matrix.
   3.  Let help also hold the <1,1> number in the matrix.
   4.  Repeat the following for each row of the matrix
   5.     Set current to the 1st number in the row
   6.     Repeat the following until all numbers are considered:
   7.        If the value of current is greater than that of help
             then replace help's value with that of current.
   8.        Set the value of current to the next number in the list
             or break if at the end of the list
   9.  The answer is the value of help.

 

Translation to Matlab code: by line number

  1. mxt = input('matrix of numbers> ');
    A user might enter the list, when prompted, like this: [1 8 2 7 ; 8 2 3 4 ; 9 1 2 3 ; 9 9 1 1] as a simple example.
  2. current = mxt(1,1);
    Use assignment (=) to change or set a value of a variable.
  3. help = current;
    Same idea as above.
  4. for i=1:size(mxt)(1)
    This ensures all rows will be considered. Index i will be used to reference all numbers in sequence.
  5. for j=1:size(mxt)(2)
    This ensures all numbers in row i will be considered. Index j will be used to reference all numbers in sequence.
  6. current = mxt(i,j);
    Use i and j to easily access the next number in the list.
  7. if current > help
    Simple comparison.
  8. help = current;
    Simple replacement using assignment. At this point there needs to be an end to define the scope of the if and another end to define the scope of the for.
  9. fprintf('%d\n',help)
    Just one of numerous ways to provide output - in this case to the console.

 

End result: an additional check on the length of the list is made at the very beginning to prevent a crash if the length of the list is 0.

    mxt = input('matrix of numbers> ');
    if size(mxt)(1) > 0 && size(mxt)(2) > 0
       help = mxt(1,1);
       for i=1:size(mxt)(1)
          for j=1:size(mxt)(2)
             current = mxt(i,j);
             if current > help help = current; end
          end
       end
       fprintf('%d\n',help);
    end