For loop changing variables and comparing results

4 ビュー (過去 30 日間)
Justin Hayes
Justin Hayes 2020 年 5 月 8 日
回答済み: Ameer Hamza 2020 年 5 月 8 日
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 Center および File Exchange2-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