MATLAB: Creating a column vector for each variable in a for loop

column vectorfor loop

Here is my code:
D=[1 4 7 5];
for i=1:length(D)
A=D(1,i)
B=A+3
C=B-5
end
How do I create a column vector of values for each variable in the for loop (I want a column vector for all the A values, another column vector for all the B values, and one last column vector for all the C values?

Best Answer

You would just index into the destination variables in the for loop, the same way you index into the origin vector. Optionally, you would also predeclare the outputs:
D=[1 4 7 5];
A = zeros(numel(D), 1);
B = zeros(numel(D), 1);
C = zeros(numel(D), 1);
for i = 1 : numel(D)
A(i, 1) = D(i); %or simply A(i) = D(i), if A is predeclared
B(i) = A(i) + 3;
C(i) = B(i) - 5;
end
However, for arithmetic operations like that, you shouldn't use a for loop and just operate on the whole vector at once. Since you start with a row vector and want columns vector, at some point you need to transpose the result:
A = D.';
B = A + 3;
C = B - 5;