# How to use for loops for splitting a domain in MatLab?

11 views (last 30 days)
Andrei on 15 Nov 2022
Answered: Voss on 15 Nov 2022
Let's say I have a domain from 0 to 10 such that 0<= x <= 10 (measurements in radians)
And let's call y = sin(x)
I want to change that domain into increments of 0.5, 0.1, 0.05, and 0.01 such that I have 4 cases (case 1 = 0, 0.5, 1, 1.5, 2, ... case 2 = 0, 0.1, 0.2, 0.3, 0.4, .... case 3 = 0, 0.05, 0.10, 0.15, 0.20, .... and case 4 = 0, 0.01, 0.02, 0.03, 0.04, ....) and I want to plot y as a function of x for all cases using a for loop.
Firstly, would I be able to split the domain into an X amount of cases using a for loop? And secondly, can I use a for loop to plot the function for all the cases?
I know how to do them individually, like for example
x_1 = 0:0.5:10;
y_1 = sin(x_1);
hold on;
plot(x_1,y_1);
x_2 = 0:0.1:10;
y_2 = sin(x_2);
plot(x_2,y_2);
x_3 = 0:0.05:10;
y_3 = sin(x_3);
plot(x_3, y_3);
x_4 = 0:0.01:10;
y_4 = sin(x_4);
plot(x_4, y_4);
hold off;
but I do not see this as good practice because if there were more than 10 cases it would be a very inefficient way of coding.

Voss on 15 Nov 2022
increments = [0.5 0.1 0.05 0.01];
for ii = increments
x_1 = 0:ii:10;
y_1 = sin(x_1);
hold on;
plot(x_1,y_1);
end ### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2022b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!