I would like to write a for loop to store all values of y when A=1,2,3,4,5. into a variable y1,y2,y3,y4,y5 respectively. Any help will be greatly appreciated. Thanks
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Rufus Adjetey
le 23 Mai 2022
Commenté : Rufus Adjetey
le 23 Mai 2022
x = -3:0.1:3;
for A = 1:1:5
y = A*sin(x);
end
plot(x,y)
0 commentaires
Réponse acceptée
James Tursa
le 23 Mai 2022
Modifié(e) : James Tursa
le 23 Mai 2022
No loop needed, and no need to create multiple variables to hold results. Just use implicit array expansion and hold results in a 2D matrix. E.g.,
x = -3:0.1:3; % row vector
A = (1:1:5)'; % column vector
y = A.*sin(x); % implicit array expansion used here, matrix = column .* row
plot(x,y)
5 commentaires
James Tursa
le 23 Mai 2022
Modifié(e) : James Tursa
le 23 Mai 2022
If the variables will have different sizes, then I would suggest you first look into cell arrays. They are built using the curly braces { }. E.g., maybe something like this would work for your purpose:
A = 1:1:5;
for k=1:numel(A)
y{k} = A(k)*sin(x);
end
Then downstream in your code you use y{1}, y{2}, etc. instead of y1, y2, etc.
So you can still use indexing in your code, and the individual cell elements y{1}, y{2}, etc. can be completely different sizes. This method is also discussed in the link I posted above.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!