Creating one array of columns from Matlab Meshgrid

I am working on an open source that needs to have a mesh file which is a 1D array. I am creating a grid via MESHGRID in Matlab and then using a FOR loop on the data column stack to create the file. It will take a very long time due to the FOR loop. Can anyone suggest me a better algorithm for this problem that will speed up my process. thank you in advance

clear all;
clc;
close all;

th = (0:0.5:360)*pi/180;
r = 0:0.2:1;
z = 5:.01:15;
[TH,R,Z] = meshgrid(th,r,z);
[X,Y,Z1] = pol2cart(TH,R,Z);




L1 = length(X(:,1,1))
L2 = length(Y(1,:,1))
L3 = length(Z1(1,1,:))

T = 1;

for i = 1:1:L1

    for j = 1:1:L2

        for k = 1:1:L3

         M(T,1) = X(i,j,k) ;
         M(T,2) = Y(i,j,k) ;
         M(T,3) = Z1(i,j,k) ; 
         T = T+1

       end


     end

 end



  dlmwrite('hpts.in',M,'precision','%2.2f','delimiter',' ','-append');

      

+3


source to share


2 answers


It is not simple:

M = [X(:), Y(:), Z1(:)]

      



Although to get technically the same result, you first calculate by the third dimension, when the Matlab methods (:)

are the primary columns, that is, they go by size 1 first, so you need to reorder the dimensions, so use permute

either (:)

or reshape

. With help, reshape

you can use the anonymous function neatly:

columize = @(A)reshape(permute(A, [3,2,1]), [],1,1)
M = [columize(X), columize(Y), columize(Z1)]

      

0


source


hacked into pol2cart.m

and used a custom version meshgrid

to achieve the desired result with this code -

%// Inputs
th = (0:0.5:360)*pi/180;
r = 0:0.2:1;
z = 5:.01:15;

%// Start processing
Mcol1 = cos(th)'*r;                      %//'
Mcol1 = repmat(Mcol1(:).',numel(z),1);   %//'

Mcol2 = sin(th)'*r;                      %//'
Mcol2 = repmat(Mcol2(:).',numel(z),1);   %//'

M = [Mcol1(:) Mcol2(:) repmat(z(:),numel(r)*numel(th),1)];

dlmwrite('hpts.in',M,'precision','%2.2f','delimiter',' ','-append');

      



It seems to be about faster than the code you would get with pre-distribution on my system. 6x

M

Alternatively, you can store the transposition th

into a variable and use it in two places where those transposition values ​​are used - cos(th)'

and sin(th)'

so this should speed it up.

0


source







All Articles