Save each vector iteration into a matrix

5 visualizaciones (últimos 30 días)
Abdur Rahim
Abdur Rahim el 31 de Oct. de 2016
Comentada: Abdulramon Adeyiola el 4 de Mzo. de 2022
I have 2 vectors, a and b and the sum of both is v.The time t ranges from 0 to 20 and i would like to save each iteration of v (a vector) into a matrix (where there are 21 vectors thus 3x21). Currently this code goes through each iteration however overwrites all of them and only shows the last value of t. Im am also unsure where the 'if' command is suitable in this circumstance.
for t=1:20;
a = [t,cos(t),0]';
b = [0,0,sin(t)]';
v = a + b;
end

Respuesta aceptada

Cory Johnson
Cory Johnson el 1 de Nov. de 2016
There are lots of ways to organize data in MATLAB. Below I have shown 3 ways to do this. I think you're looking for the last method.
%%Cell Array
for t=0:20;
a{t+1} = [t,cos(t),0]';
b{t+1} = [0,0,sin(t)]';
v{t+1} = a{t+1} + b{t+1};
end
%%Structure array
for t=0:20;
vec(t+1).a = [t,cos(t),0]';
vec(t+1).b = [0,0,sin(t)]';
vec(t+1).v = vec(t+1).a + vec(t+1).b;
end
%%Only save v
v = [];
for t=0:20;
a = [t,cos(t),0]';
b = [0,0,sin(t)]';
v = [v, (a + b)];
end
Hope that helps!
  2 comentarios
Abdur Rahim
Abdur Rahim el 1 de Nov. de 2016
It's greats having all those methods because I can use the format for future codes, its helped me a lot thanks.
Abdulramon Adeyiola
Abdulramon Adeyiola el 4 de Mzo. de 2022
Thanks for this. Meanwhile, what if the dimension of the two vectors are not the same?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Multidimensional Arrays 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!

Translated by