For loop changing variables and comparing results

5 次查看(过去 30 天)
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?

采纳的回答

Isiah Pham
Isiah Pham 2020-5-8
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 个评论
Justin Hayes
Justin Hayes 2020-5-8
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 2020-5-8
编辑:Isiah Pham 2020-5-8
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)

请先登录,再进行评论。

更多回答(1 个)

Ameer Hamza
Ameer Hamza 2020-5-8
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)

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by