# Matlab command while

matlab command "while"

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)
i=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

I'm sorry, but what is i doing here? I don't see how you are referencing it.

sorry, i meant to be n

You're somehwat close. Your function is setting the max to the value specified by a(n), which in this case is a(1,1). Your while loop, however, only works when the a(n) is < max. Earlier in the problem, you defined the max and a(n) to be equal, so the loop will not run.

What you want to do is index the entire matrix so you can check each value at each position, and then compare all of the values to find out which one is the largest value.

The first thing you want to do is find the number of elements in the matrix because this will tell you the number of indices. The numel() function does this, and you can also find it by multiplying the number of rows and columns together.

Then you need to set up the while loop to run from the first index to the last index, so you will want to use:

n = 1
while n <= number of elements in the matrix
n = n + 1
(conditional statement)
end

This will check each value in the matrix

The next thing you want to do is compare each value to one another using a conditional. You should have the conditional be run on if the value at a(n) is larger than the value set as the max value.
The code should look something like this:

if a(n) > max
max = a(n)
end

Putting all fo this together:

a = rand(5)
n = 1
max = a(n)
while n <= numel(a)
if a(n) > max
max = a(n)
end
n = n + 1
end

I hope this was what you were looking for!

perfect, thanks,