For loop changing variables and comparing results
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Justin Hayes
le 8 Mai 2020
Réponse apportée : Ameer Hamza
le 8 Mai 2020
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 commentaires
Réponse acceptée
Isiah Pham
le 8 Mai 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 commentaires
Isiah Pham
le 8 Mai 2020
Modifié(e) : Isiah Pham
le 8 Mai 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)
Plus de réponses (1)
Ameer Hamza
le 8 Mai 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)

0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!