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

조회 수: 23 (최근 30일)
Bob
Bob 2014년 12월 13일
댓글: Christof Omar 2017년 12월 20일
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