loop over list in matlab

In MATLAB, the standard way to loop over a list is using a for loop as follows:

main.m
list = [1, 2, 3, 4, 5];
for i = 1:length(list)
    % access the i-th element of the list using list(i)
    fprintf('Element %d: %d\n', i, list(i));
end
152 chars
6 lines

This will iterate over the list and print out each element along with its index. You can replace the fprintf line with any code that you want to execute for each element of the list.

Alternatively, you can use the while loop to iterate over a list if you don't know the exact number of elements beforehand. Here's an example:

main.m
list = [1, 2, 3, 4, 5];
i = 1;
while i <= length(list)
    % access the i-th element of the list using list(i)
    fprintf('Element %d: %d\n', i, list(i));
    i = i + 1;
end
175 chars
8 lines

This code does the same thing as the previous example, but using a while loop instead of a for loop.

related categories

gistlibby LogSnag