Effacer les filtres
Effacer les filtres

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

6 vues (au cours des 30 derniers jours)
Bob
Bob le 13 Déc 2014
Commenté : Christof Omar le 20 Déc 2017
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?

Réponse acceptée

Guillaume
Guillaume le 13 Déc 2014
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;

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by