create a loop with a range in matlab

You can use a for loop with the : operator to iterate over a range of values. The syntax is as follows:

main.m
for x = start:step:end
    % loop contents go here
end
55 chars
4 lines

where start is the starting value, step is the step size, and end is the end value. For example, the following code will loop over the numbers from 1 to 10 incrementing by 2:

main.m
for x = 1:2:10
    disp(x);
end
32 chars
4 lines

This will output:

main.m
1
3
5
7
9
10 chars
6 lines

You can also use the linspace function to create a range of linearly spaced values, and then loop over those values. The syntax is as follows:

main.m
values = linspace(start, end, num_steps);
for x = values
    % loop contents go here
end
89 chars
5 lines

where start is the starting value, end is the end value, and num_steps is the number of steps (i.e. the length of the range). For example, the following code will loop over the numbers from 0 to 1.5 with 4 steps:

main.m
values = linspace(0, 1.5, 4);
for x = values
    disp(x);
end
62 chars
5 lines

This will output:

main.m
0
0.5
1
1.5
12 chars
5 lines

related categories

gistlibby LogSnag