Creating a column vector for each variable in a for loop?
28 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Bob
el 13 de Dic. de 2014
Comentada: Christof Omar
el 20 de Dic. de 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?
0 comentarios
Respuesta aceptada
Guillaume
el 13 de Dic. de 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;
1 comentario
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!