storing data in a matrix from a nested loop

I want to save the vector made from d12 each time i.e. d12 is 4*3 matrix. d12 in nested loop
d1 = [0 0 2
0 0 -2 ];
d2 = [0 0 15
0 0 13 ];
for i = 1:2
for j = 1:2
d12() = [d1(i,:)-d2(j,:)];
end
end

 Respuesta aceptada

rajesh  regar
rajesh regar el 11 de Sept. de 2019
d1 = [0 0 2
0 0 -2 ];
d2 = [0 0 15
0 0 13 ];
k = 1;
for i = 1:2
for j = 1:2
d12(k,:) = [d1(i,:)-d2(j,:)];
k = k+1;
end
end
you can initiate k as 1 then increase it by one

2 comentarios

Stephen23
Stephen23 el 11 de Sept. de 2019
Editada: Stephen23 el 11 de Sept. de 2019
rajesh  regar
rajesh regar el 11 de Sept. de 2019
Thank you, it is really helped me

Iniciar sesión para comentar.

Más respuestas (2)

Stephen23
Stephen23 el 11 de Sept. de 2019
Editada: Stephen23 el 11 de Sept. de 2019
No loops required:
>> d1 = [0,0,2;0,0,-2]
d1 =
0 0 2
0 0 -2
>> d2 = [0,0,15;0,0,13]
d2 =
0 0 15
0 0 13
>> out = repelem(d1,size(d2,1),1) - repmat(d2,size(d1,1),1)
out =
0 0 -13
0 0 -11
0 0 -17
0 0 -15
This gives exactly the sme output as your nested loops:
>> isequal(out,d12)
ans =
1

2 comentarios

madhan ravi
madhan ravi el 11 de Sept. de 2019
+1 , far more elegant :)
rajesh  regar
rajesh regar el 11 de Sept. de 2019
Thank you, I have to use loop for solving my problem because I need to define more variable and finally I will put in formula. Also the size of nested loop in my case is aroung 1000*1000 i.e. need to vary i = 1:1000 and j = 1:1000.

Iniciar sesión para comentar.

madhan ravi
madhan ravi el 11 de Sept. de 2019
Editada: madhan ravi el 11 de Sept. de 2019
[m,n]=size(d1);
[m1,n1]=size(d2);
z = permute(reshape(d1.',1,n,m) - d2,[2,1,3])
d12 = reshape(z,n,[]).'
% Or if you prefer a loop
k = 1;
d12 = zeros(m+m1,n); % preallocate
for ii = 1:m % don't hardcode the sizes , use size() instead
for jj = 1:m1
d12(k,:) = d1(ii,:) - d2(jj,:);
k = k+1;
end
end

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 11 de Sept. de 2019

Comentada:

el 11 de Sept. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by