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

2 views (last 30 days)
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...

Accepted Answer

Jakob B. Nielsen
Jakob B. Nielsen on 21 Jan 2020
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!