MATLAB: How to save every answers in matrix with 2 for loops.

for loopmatrixsave

Hi,I am a student,so I have a trouble to this problem.
I want to create a 16*3 matrix that save every loop answer.
right now I have
d1=[0.25 6.25 0.25; 1 4 1; 2.25 2.25 2.25; 4 1 4]
d2=[0.25 0.25 6.25; 1 1 4; 2.25 2.25 2.25; 4 4 1]
for k=1:4
for j=1:4
(d1(k,:)+d2(j,:))
end
end
the answer is a 1*3 matrix every time,
for loop,I have 16 time answer,
so I want to save every iteration loop answer .

Best Answer

You don't need loops, with the correct indices and one simple addition:
>> [X,Y] = ndgrid(1:4);
>> d1(X(:),:) + d2(Y(:),:)
ans =
0.50000 6.50000 6.50000
1.25000 4.25000 7.25000
2.50000 2.50000 8.50000
4.25000 1.25000 10.25000
1.25000 7.25000 4.25000
2.00000 5.00000 5.00000
3.25000 3.25000 6.25000
5.00000 2.00000 8.00000
2.50000 8.50000 2.50000
3.25000 6.25000 3.25000
4.50000 4.50000 4.50000
6.25000 3.25000 6.25000
4.25000 10.25000 1.25000
5.00000 8.00000 2.00000
6.25000 6.25000 3.25000
8.00000 5.00000 5.00000