# how to store each for loop values in multidimensional matrix?

2 views (last 30 days)
Shiv Karpoor on 5 Mar 2022
Commented: Shiv Karpoor on 6 Mar 2022
Hello MATLAB Community,
I am finding a little problem to store values of each of the for loop iteration into a multi dimensional matrix.
below is my code:
zn = 3; % no. of planes
zmax = 200; % z max
zmin = 100; % z min
zA = linspace(zmax,zmin,zn); % linearly distributed z planes between z max & z min
phiA = (-180:180); % phi value from phi min to phi max
thetaA = (-180:180); % theta value from theta min to theta max
for zi = 1:length(zA)
z = zA(zi);
for phii = 1:length(phiA)
phi = (phiA(phii));
for thetai = 1:length(thetaA)
theta = (thetaA(thetai));
px = phi + theta;
py = phi - theta;
P = [px; py; z];
if px>-30 && px<30 && py>-30 && py<30
S(:,:,z) = P(:)';
end
end
end
fprintf('Processing %d of %d ...',zi,zn); % progress
fprintf('done.\n'); % display when done
end
Since, I am creating 3 planes for this example. When I type S(:,:,3), I should be only able to store and access all the points (px & py) in that particular plane 3. Similarly S(:,:,2) should only store and access all points in plane 2,
but when I say S(:,:,z) I should be able to access & store all values of px & py of all planes.
But in my code, I am not able to do the above.
In my code, all values are being stored in multidimensional matrix and I am not able to differeiante the values according to the z planes.
Since number of planes are 3, there should be only 3 pages for the matrix 'S'.
Thank you in advance!!
I really appreciate your help.
Kind regards,
Shiv

Simon Chan on 5 Mar 2022
Try to use a cell array to store the result as follows:
zn = 3; % no. of planes
zmax = 200; % z max
zmin = 100; % z min
zA = linspace(zmax,zmin,zn); % linearly distributed z planes between z max & z min
phiA = (-180:180); % phi value from phi min to phi max
thetaA = (-180:180); % theta value from theta min to theta max
for zi = 1:length(zA)
z = zA(zi);
Pall = []; % Initialize
for phii = 1:length(phiA)
phi = (phiA(phii));
for thetai = 1:length(thetaA)
theta = (thetaA(thetai));
px = phi + theta;
py = phi - theta;
P = [px, py]; % Store value for px and py only
if px>-30 && px<30 && py>-30 && py<30
Pall = [Pall;P]; % Append the point which satisfy the condition
end
end
end
S{zi} = Pall; % Save into a cell array
fprintf('Processing %d of %d ...',zi,zn); % progress
fprintf('done.\n'); % display when done
end
Processing 1 of 3 ...
done.
Processing 2 of 3 ...
done.
Processing 3 of 3 ...
done.
S
S = 1×3 cell array
{1741×2 double} {1741×2 double} {1741×2 double}
##### 1 CommentShowHide None
Shiv Karpoor on 6 Mar 2022
Hi Simon,
Thank you for the suggestion, storing in cell array actually worked on the real problem.
I appreciate your help!
Kind regards,
Shiv