For Loop Output as a Vector

7 次查看(过去 30 天)
C
C 2017-10-1
回答: OCDER 2017-10-1
I have a function nest that performs nested multiplication. How can I put the outputs of p into the vector p4? With the following code, my output is 601 outputs of p4, rather than 1 p4 vector.
a = [0; 1; 0; -1];
p4 = zeros(1,601);
for i = 1
for z = linspace(-3,3,601)
p = nest(a,z)
p4(i) = p
end
end
  1 个评论
Stephen23
Stephen23 2017-10-1
" my output is 601 outputs of p4, rather than 1 p4 vector."
I doubt that. Your code certainly displays variable p on every iteration, but that is totally unrelated to any "output". If you do not want to display p on every iteration then you need a semicolon to repress display:
a = [0; 1; 0; -1];
p4 = zeros(1,601);
for i = 1
for z = linspace(-3,3,601)
p = nest(a,z); % <- semicolon!
p4(i) = p; % <- semicolon!
end
end
Note that
for i = 1
is unlikely to to be useful for you.

请先登录,再进行评论。

回答(1 个)

OCDER
OCDER 2017-10-1
a = [0; 1; 0; -1];
p4 = zeros(1, 601);
z = linspace(-3,3,601); %leave z as a matrix, instead of using it as a for loop counter
for k = 1:length(z) %try to reserve for loop counters for iteration number (integer). This can be used as index to p4 too.
p4(k) = nest(a, z(k)); %store results directly to kth index of p4. Use kth z value for calc.
end
Now, if you wrote your nest function in a way to handle vector input (z), you could have also done this to avoid the for loop. It's called vectorizing your code .
a = [0; 1; 0; -1];
p4 = nest(a, linspace(-3,3,601));
This is better because there is
  • no need to initialize p4
  • no need to make z vector (assuming that was a temporary vector)
  • no need to use a for loop, which requires assigning and tracking loop counters
Vectorized code is usually faster and easier to read, BUT, don't add the for loop inside the nest function, which would defeat the purpose of vectorization. Read more about vecotrization here: https://www.mathworks.com/help/matlab/matlab_prog/vectorization.html

类别

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