Defining multiple variables in a single loop

2 vues (au cours des 30 derniers jours)
naveed bashir
naveed bashir le 17 Nov 2020
Good afternoon,
I am trying to define three variables in a loop a,b and c in the following way:
for a=2:49
for b= 52:99
for c=1:48
derives(a)= x(b)/m;
derives(b) = k*x(c)- 2*k*x(c+1)+ k*x(c+2);
end
end
end
But this method does not give me the results I want, In fact my supervisor told me that I am not using a loop at all!
I tried putting the code between each for loop, but then the other variables are undefined
Could anyone please suggest an alternative method in which I can define all three variables in a for loop?
Thanks

Réponses (1)

Steven Lord
Steven Lord le 17 Nov 2020
You are, of course, using a loop. I suspect what your supervisor told you (or intended to tell you) is that you don't need to use loops here. You can vectorize the calculations by operating on pieces of the x array that are larger than single elements.
x = 1:5;
whereToStore = 3 + (1:numel(x)); % Store in elements 4 (3+1) to 8 (3+5)
y(whereToStore) = x.^2
y = 1×8
0 0 0 1 4 9 16 25

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by