for loop to find max in matlab

Here's an example of using a for loop to find the maximum value of an array in Matlab:

main.m
array = [5, 3, 8, 2, 7, 1];
maximum = array(1);

for i = 2:length(array)
    if array(i) > maximum
        maximum = array(i);
    end
end

disp(maximum); % outputs 8
167 chars
11 lines

In this example, we first define an array of numbers. We then initialize a variable 'maximum' to the first element in the array. We loop through the array using a for loop starting at the second element (since we already set 'maximum' to the first element). In each iteration of the loop, we check if the current element is greater than the current maximum. If it is, we update 'maximum' to that element. Finally, we output the value of 'maximum' to the console. Note that you can adapt this for loop to work with any array, regardless of its size or elements.

gistlibby LogSnag