Defining multiple variables in a single loop

4 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by