For Loop Output as a Vector

7 views (last 30 days)
C
C on 1 Oct 2017
Answered: OCDER on 1 Oct 2017
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 Comment
Stephen23
Stephen23 on 1 Oct 2017
" 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.

Sign in to comment.

Answers (1)

OCDER
OCDER on 1 Oct 2017
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!