MATLAB: How to store each iteration data, which is having multiple loops

for loopiterationMATLABmatrixoptimization

Hai,
I have two for loop in a program, one for iteration and other for matrix formation. I need to store all iteration data together.
sample program:
for i = 1:3
for j = 1:10
x1 = 3*rand(1,1);
x2 = 4*rand(1,1);
x3 = 5*rand(1,1);
x = [x1, x2, x3];
s(j,:) = x;
end
s
end
I need to store s1, s2, s3 together to another variable p.
Thanking You…

Best Answer

You can add a third dimension to your matrix easily enough, your result p will now be a 3D matrix. (You can even add a 4th dimension and beyond, but it becomes harder and harder to "imagine" in your head ;) )
for i = 1:3
for j = 1:10
x1 = 3*rand(1,1);
x2 = 4*rand(1,1);
x3 = 5*rand(1,1);
x = [x1, x2, x3];
s(j,:) = x;
end
p(:,:,i)=s;
end
Or, another approach would be to use a structure, depending on your preference really.
for i = 1:3
for j = 1:10
x1 = 3*rand(1,1);
x2 = 4*rand(1,1);
x3 = 5*rand(1,1);
x = [x1, x2, x3];
s(j,:) = x;
end
p(i).sdata=s;
end