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.
回答(2 个)
Walter Roberson
2022-11-8
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 个评论
Walter Roberson
2022-11-9
编辑:Walter Roberson
2022-11-9
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)
类别
在 帮助中心 和 File Exchange 中查找有关 MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!