MATLAB: How to prevent output being overwritten in for loop

foorloop

I have a for loop and want to get a matrix called P as output. I want to get different values in P for each iteration and want to print it as P1, P2, P3…Pn. I tried the below code but, I got only Pn here. How can I modify this?
n=size(Image);
for i=1:n
for j=1:n
a11=Ix(i,j)./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a12=-Iy(i,j)./Ig(i,j);
a13=-mu.*Ix(i,j)./sqrt(1+mu.^2.*Ig(i,j).^2);
a21=Iy(i,j)./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a22=Ix(i,j)./Ig(i,j);
a23=-mu.*Iy(i,j)./sqrt(1+mu.^2.*Ig(i,j).^2);
a31=mu.*Ig(i,j).^2./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a32=0;
a33=1./sqrt(1+mu.^2.*Ig(i,j).^2);
end
P=[a11 a12 a13; a21 a22 a23; a31 a32 a33];
end

Best Answer

You have
for j=1:n
a11=Ix(i,j)./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a12=-Iy(i,j)./Ig(i,j);
a13=-mu.*Ix(i,j)./sqrt(1+mu.^2.*Ig(i,j).^2);
a21=Iy(i,j)./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a22=Ix(i,j)./Ig(i,j);
a23=-mu.*Iy(i,j)./sqrt(1+mu.^2.*Ig(i,j).^2);
a31=mu.*Ig(i,j).^2./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a32=0;
a33=1./sqrt(1+mu.^2.*Ig(i,j).^2);
end
every iteration of that overwrites all of the variables. You should not bother to do the iterations before j = n, or you should save all of the outputs, such as
for j=1:n
a11(j)=Ix(i,j)./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a12(j)=-Iy(i,j)./Ig(i,j);
a13(j)=-mu.*Ix(i,j)./sqrt(1+mu.^2.*Ig(i,j).^2);
a21(j)=Iy(i,j)./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a22(j)=Ix(i,j)./Ig(i,j);
a23(j)=-mu.*Iy(i,j)./sqrt(1+mu.^2.*Ig(i,j).^2);
a31(j)=mu.*Ig(i,j).^2./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a32(j)=0;
a33(j)=1./sqrt(1+mu.^2.*Ig(i,j).^2);
end
Now when you reach
P=[a11 a12 a13; a21 a22 a23; a31 a32 a33];
you have to decide how you want those vectors to go together. Perhaps you want
P=[a11(:) a12(:) a13(:); a21(:) a22(:) a23(:); a31(:) a32(:) a33(:)];
After that you face the problem that you want to save that P for every i. That could lead to
P{i}=[a11(:) a12(:) a13(:); a21(:) a22(:) a23(:); a31(:) a32(:) a33(:)];
However... my suspicion is that what you want is really,
n = size(Image, 1);
m = size(Image, 2);
P = cell(n, m);
for i=1:n
for j=1:m
a11=Ix(i,j)./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a12=-Iy(i,j)./Ig(i,j);
a13=-mu.*Ix(i,j)./sqrt(1+mu.^2.*Ig(i,j).^2);
a21=Iy(i,j)./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a22=Ix(i,j)./Ig(i,j);
a23=-mu.*Iy(i,j)./sqrt(1+mu.^2.*Ig(i,j).^2);
a31=mu.*Ig(i,j).^2./sqrt(Ig(i,j).^2.*(1+mu.^2.*Ig(i,j).^2));
a32=0;
a33=1./sqrt(1+mu.^2.*Ig(i,j).^2);
P{n, m}=[a11 a12 a13; a21 a22 a23; a31 a32 a33];
end
end