how to store each for loop values in multidimensional matrix?
6 views (last 30 days)
Show older comments
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'.
Can anyone please help me with any suggestions.
Thank you in advance!!
I really appreciate your help.
Kind regards,
Shiv
0 Comments
Accepted Answer
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
S
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!