Is it possible to loop through 3D coordinates in a meshgrid using only one for loop?
Show older comments
I have created a square meshgrid containing the Cartesian coordinates of a region in a 3D space. Now, I want to loop through each of the coordinates using a single for loop. Is there a way to linearize this grid in coordinate by coordinate basis? Essentially, I want to call each cooridnate during each loop. Is it doable in anyway?
I know it can be done using nested loops, but I am trying to avoid that to reduce the execution time. Thanks in advacne.
Answers (2)
Walter Roberson
on 8 Nov 2022
for idx = 1 : numel(X3D)
this_x = X3D(idx); this_y = Y3D(idx); this_z = Z3D(idx);
stuff involving this_x, this_y, this_z
end
but this will probably not be notably faster than three nested loops. You should consider using vectorized calculations (over at least one dimension) instead of indexing over each coordinate in turn.
2 Comments
Walter Roberson
on 9 Nov 2022
Edited: Walter Roberson
on 9 Nov 2022
position_grid = meshgrid(x_coor,y_coor,z_coor);
meshgrid emits one output per dimension, so that call is only going to be returning the 3D X coordinates, not the Y or Z. You would need
[X3D, Y3D, Z3D] = meshgrid(x_coor,y_coor,z_coor);
or equivalent.
Euclidean distance from the origin, without generating and saving explicit coordinate lists, is
D = sqrt( reshape(x_coor, [], 1, 1).^2 + reshape(y_coor, 1, [], 1).^2 + reshape(z_coor, 1, 1, []).^2 );
This would be an array that is length(x_coor) by length(y_coor) by length(z_coor)
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!