For loop changing variables and comparing results
2 次查看(过去 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?
0 个评论
采纳的回答
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 个评论
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
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)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/291523/image.png)
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!