Defining multiple variables in a single loop

3 ビュー (過去 30 日間)
naveed bashir
naveed bashir 2020 年 11 月 17 日
回答済み: Steven Lord 2020 年 11 月 17 日
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

回答 (1 件)

Steven Lord
Steven Lord 2020 年 11 月 17 日
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by