For-loop using only last iteration

15 views (last 30 days)
My code is as follows:
clearvars;
zeros(1,10); %Create a row vector with 10 zeros
for i=1:1:10
A = [i.^2];
C = zeros(1,10) + A;
end
disp(C)
100 100 100 100 100 100 100 100 100 100
Now, what I originally wanted to do was add the square of each iteration on the respective i-th column of the zeros(1,10) vector, instead I get i = 10 for every position and I don't understand why it doesn't do it for each iteration but only for the last one.
  3 Comments
Torsten
Torsten on 25 Oct 2022
x = (1:10).^2
x = 1×10
1 4 9 16 25 36 49 64 81 100

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 25 Oct 2022
It is necessary to index into ‘C’, however I do not know what you want as the result.
% clearvars;
C = zeros(1,10); %Create a row vector with 10 zeros
for i=1:1:10
A = [i.^2];
C(i) = A;
end
disp(C)
1 4 9 16 25 36 49 64 81 100
.
  3 Comments
Star Strider
Star Strider on 25 Oct 2022
@Giuliano — As always, my pleasure!
The problem is that you did not index ‘C’, so every iteration overwrote the previous iteration.
I also assigned the zeros call before the loop to ‘C’ since your obvious intent was to pre-allocate it. That should always be done if at all possible, so that is good programming practice there.
@Matt JThank you!

Sign in to comment.

More Answers (1)

Jim Riggs
Jim Riggs on 25 Oct 2022
Edited: Jim Riggs on 25 Oct 2022
Inside the loop
C = zeros(1,10) + A;
the function "zeros(1,10)" is assigning zeros to the entire C vector, then adding A.
Also, the command before the for loop "zeros(1,10)" does not save the 10 element vector.
I think what you intended is something like:
C = zeros(1,10); %Create a row vector with 10 zeros
for i=1:1:10
A = [i.^2];
C(i) = A;
end
  3 Comments
Giuliano
Giuliano on 25 Oct 2022
Thanks for the detailed explanation! Honestly I thought what would happen if I somehow included i in C was that I‘d get ten vectors C that have i^2 as the i-th element and the rest zeros and that I‘d have to somehow add these then vectors then. Might be stupid, but I just started with MatLab (rather any kind of programming) last week so let me be excused! Thanks again.

Sign in to comment.

Categories

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

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by