For loop changing variables and comparing results

4 views (last 30 days)
time_range = 10;
y = zeros(1,time_range);
for t = 1:1:length(time_range)
x = 0.5;
y(t) = x .* t;
end
plot(time_range,y)
If I want to change x from 0.5 to 1 and compare the results on the same graph how would I do this? I do not want to simply copy and paste the for loop again and change the value of x. Is there a way to do this?

Accepted Answer

Isiah Pham
Isiah Pham on 8 May 2020
time_range = 10;
y = zeros(1,time_range);
for x = 0.5:0.5:1
for t = 1:1:length(time_range)
x = 0.5;
y(t) = x .* t;
end
hold on
plot(time_range,y)
end
Just do the same code but put it in a for loop where x goes from 0.5 to 1
  2 Comments
Justin Hayes
Justin Hayes on 8 May 2020
Thank you. I think I understand what you mean, however, when I used this code it produces an empty plot. Any suggestions?
Isiah Pham
Isiah Pham on 8 May 2020
Edited: Isiah Pham on 8 May 2020
tme_range is a single number the length of time_range is one so t is only run once. When t is plotted against y, it plots pne thing all at 10,y. If you would want a line of 0.5x or 1x, plot basically puts a bunch of points from the first and second inputs and draws a line between each.
plot(a,b) would make a point at (a(1),b(1)), (a(2), b(2)), etc. and then draw a graph
If I was doing this problem, I would instead just have a set of x-values and y-values without the time_range:
%X-values
x = [1:10]
%Loop runs the same plot for y = 0.5x and y = 1x
for coeff = 1:2
%Makes the same x-matrix for y but times 0.5 or 1
y = 0.5*coeff.*x
%Plots x against y
hold on
plot(x,y)
end
If you want to keep the code similar to your original code, then you would have to adjust the second for loop and plot(time_range,y)

Sign in to comment.

More Answers (1)

Ameer Hamza
Ameer Hamza on 8 May 2020
In MATLAB, you can make the code simpler and easy to read by replacing for-loop with vectorized operations.
time_range = 1:10;
x = 0.5:0.1:1;
y = x(:).*time_range;
plot(time_range,y)

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!