Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

While command in MATLAB

  1. Apr 24, 2009 #1
    we recently learned about loops in matlab, more specifically the while command, from what i understand, matlab will continue with the set command as long as the condition i chose is true.

    as an excercise we had to make a program that will give me the highest value in a given matrix

    what i tried doing was:

    a=rand(5)
    n=1
    max=a(n)
    while a(n)<max
    n=n+1;
    max=a(n);
    end

    what i thought this would do was take a random 5x5 matrix, start from a(1,1) and find the largest value,,, not so,

    how can i make such a program using "while", not "if", what i want it to do is take a loop and keep on adding 1 to the previous n, keeping the largest value as max
     
  2. jcsd
  3. Apr 24, 2009 #2

    Hootenanny

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Well the first problem is that a is a 5x5 array and by using a(n) you are only accessing the nth row of the matrix rather than each individual element. To examine each element you need to use two nested while loops as well as an if command.

    Something like the following should work,

    Code (Text):

    max = 0; m=1; n=1;
    matrix = rand(5);

    while m <= size(matrix,1)
         while n <=size(matrix,2)
              if matrix(m,n) > max
                   max = matrix(m,n);
              end
              n=n+1;
         end
         m=m+1;
    end

    max
     
    If you don't understand any of the commands that I have used, or don't understand why I have used them please do ask.
     
    Last edited: Apr 24, 2009
  4. Apr 24, 2009 #3
     
  5. Apr 24, 2009 #4
    thanks for the help, got it

    a=rand(5);
    n=1;
    mx=0;
    b=size(a);
    while n<=b(1)*b(2);
    if mx<a(n);
    mx=a(n);
    end
    n=n+1;
    end

    mx
     
  6. Apr 24, 2009 #5

    Hootenanny

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I didn't know that, but it's something that I'll have to remember! Thanks.
    Excellent - you did it even without my help :redface:

    Anyway, I found the error in my code. The column counter n needs to be reset for each new row m:
    Code (Text):

    max = 0; m=1; n=1;
    matrix = rand(5);

    while m <= size(matrix,1)
         while n <=size(matrix,2)
              if matrix(m,n) > max
                   max = matrix(m,n);
              end
              n=n+1;
         end
         m=m+1;
         n=1;
    end

    max
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: While command in MATLAB
Loading...