Way To Freedom…

Icon

read, digest, think, and write..

matlab: ndgrid function

Just noticed in MATLAB google groups, in this thread. There is a function preventing us to write nested loops i.e ndgrid.

Here the original code :

for habs=0:.25:1
for pabs=0:.2:1
for beta=0:pi/2:2*pi
for alpha=0:pi/5:2*pi

H=habs*(cos(beta)+i*sin(beta));
p=pabs*(cos(alpha)+i*sin(alpha));
W=abs(H)^2*abs(p)*(2*exp(i*(alpha-beta))+ exp(-i*(alpha-  beta)))*exp(i*beta);
plot(real(W+H),imag(W+H),’o’,’MarkerSize’,4)
hold on

end
end
end
end

With ndgrid function, the code becomes :

[habs,pabs,beta,alpha]=ndgrid(0:.25:1,0:.2:1, 0:pi/2:2*pi,0:pi/5:2*pi);
H=habs.*(cos(beta)+i*sin(beta));
p=pabs.*(cos(alpha)+i*sin(alpha));
W=abs(H).^2.*abs(p).*(2*exp(i*(alpha-beta))+ exp(-i*(alpha-beta))).*exp(i*beta);

W=W(:);
H=H(:);
plot(real(W+H),imag(W+H),’o’,’MarkerSize’,4)

Further, you may check the run time. Which one faster ?

Filed under: PhD Study

One Response

  1. willezumleben says:

    Ka, bulan November gw mau ke Norway.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: