Vectorising a Meshgrid Coordinate Construction
3 次查看(过去 30 天)
显示 更早的评论
I have three coordinate arrays (file attached) of size [M x 2], where M is the number of elements and the 2 represents different points in a 1D system. To find the 3D meshed coordinates upon which I perform calculations I use code of the form:
for ele = 1:size(X_co,1) %Loop Over Each Element
[X_cube,Y_cube,Z_cube] = meshgrid(X_co(ele,:),Y_co(ele,:),Z_co(ele,:)); %Construct Meshgrid of size [2x2x2] for an Element
X_save(:,:,:,element) = X_cube; %Save Coordinates
Y_save(:,:,:,element) = Y_cube;
Z_save(:,:,:,element) = Z_cube;
end
The solution then is of size [2x2x2xM]. My best attempt to vectorise this was:
[X_cube,Y_cube,Z_cube] = meshgrid(X_co,Y_co,Z_co);
X_save = reshape(X_cube,2,2,2,[]); Y_save = reshape(Y_cube,2,2,2,[]); Z_save = reshape(Z_cube,2,2,2,[]);
However this solution is of size [2x2x2x(M^3)] which, when plotting both solutions has many many many repeated points so doesn't actually work for my application.
Can this problem be vectorised, or is a for loop the best way to construct this coordinate array?
3 个评论
jessupj
2020-9-2
ndgrid is the way to go here i think. i think it can be done using meshgrid along with some resize + repmat statements.
采纳的回答
Bruno Luong
2020-9-2
编辑:Bruno Luong
2020-9-2
One way
[~,nx] = size(X_co);
[~,ny] = size(Y_co);
[m,nz] = size(Z_co);
[NX,NY,NZ] = meshgrid(1:nx,1:ny,1:nz);
sz = [size(NX),m];
% if you know nx, ny, nz are 2 you can replace the 5 above commands by
% [NX,NY,NZ] = meshgrid(1:2);
% sz = [2,2,2,m];
X_save = X_co.';
Y_save = Y_co.';
Z_save = Z_co.';
X_save = reshape(X_save(NX,:),sz);
Y_save = reshape(Y_save(NY,:),sz);
Z_save = reshape(Z_save(NZ,:),sz);
Note: I honestly prefer your for-loop if you add a preallocation
6 个评论
Bruno Luong
2020-9-3
"So by properly allocate you mean initialise the arrays as zeros before the for loop starts?"
Yes intiialize the 3 zeros arrays with SZ from with my code.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!