Is it possible to loop through 3D coordinates in a meshgrid using only one for loop?

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)

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

I created the grid using a code similar to the following:
% sample expected coordinates in each axis
x_coor = linspace(-10,10,10);
y_coor = linspace(0,30,10);
z_coor = linspace(85,125,10);
% Attempt to combine them
position_grid = meshgrid(x_coor,y_coor,z_coor);
May be my way of putting all the axes values in the same place isn't the most convenient way to do it. I need to use each coordinate, i.e. position = (x,y,z), for a calculation. For example, a(i) = b*position(i). Or, more speceifically, I want to know the Euclidean distance fron the origin: |(x,y,z)|. Is there a way to simply do this just using vectorization instead of loop(s)?
Note, by position(i), I meant (x(i),y(i),z(i))
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)

Sign in to comment.

I think at first all the data needs to be put in a grid, and then they need to be vectorized somehow in coordinate by coordinate basis. Creating a matrix of (x,y,z) with 3 rows and 3 columns will not work of for positions.

Categories

Products

Release

R2020a

Asked:

on 8 Nov 2022

Edited:

on 9 Nov 2022

Community Treasure Hunt

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

Start Hunting!