Creating a column vector for each variable in a for loop?

28 次查看(过去 30 天)
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?

采纳的回答

Guillaume
Guillaume 2014-12-13
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;

更多回答(0 个)

类别

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