loop for finding the max of a vector in matlab

To find the maximum value in a vector, here is an example loop in MATLAB:

main.m
vector = [3, 5, 2, 8, 1];
max_value = vector(1); % set the initial max value to the first element

for i = 2:length(vector)
    if vector(i) > max_value
        max_value = vector(i); % update max value if current element is greater
    end
end

disp(max_value); % display the max value
287 chars
11 lines

In this code block, we have a vector of values and we set the initial max value to be the first element of the vector. Then we loop through the rest of the elements and update the max value if we find an element greater than the current max value. Once we finish the loop, we have found the maximum value in the vector and can display it with the disp function.

gistlibby LogSnag