フィルターのクリア

How can vectorize the below codes?

2 ビュー (過去 30 日間)
Amir Torabi
Amir Torabi 2019 年 12 月 1 日
コメント済み: Amir Torabi 2019 年 12 月 2 日
Nx=512;
Ny=Nx
x0 = Nx/2;
y0 = Ny/2;
isolve = 2;
tic
for i=1:512
for j=1:512
ii=(i-1)*Nx+j;
if(isolve == 2)
etas(ii,1)=1.0;
phis(ii,1) =0;
phis(ii,2)=0;
etas(ii,2)=0.0;
else
etas(i,j,1) =1.0;
etas(i,j,2) =0.0;
phis(ii,1) =0;
phis(ii,2)=0;
end
xlength =sqrt((i-x0)^2+(j-y0)^2);
if(xlength <= 14)
if(isolve == 2)
etas(ii,1)=0.0;
etas(ii,2)=1.0;
phis(ii,1) =0;
phis(ii,2)=0;
else
phis(ii,1) =0;
phis(ii,2)=0;
end
end %if
end %j
end %i

採用された回答

the cyclist
the cyclist 2019 年 12 月 1 日
Well, not vectorizing it, but if you preallocate etas and phis with these line:
etas = zeros(262144,2);
phis = zeros(262144,2);
you will speed up the code by a huge factor. (For me, it was a factor of over 1000.)
  5 件のコメント
the cyclist
the cyclist 2019 年 12 月 2 日
The following is a vectorized version. It is not that much faster, and actually more difficult to understand what is going on.
Nx = 512;
Ny = Nx;
x0 = Nx/2;
y0 = Ny/2;
isolve = 2;
NxNy = Nx*Ny;
etas = [ones(NxNy,1) zeros(NxNy,1)];
phis = zeros(NxNy,2);
tic
xvec = 1:Nx;
yvec = 1:Ny;
xlength = sqrt((xvec-x0).^2+(yvec'-y0).^2);
idx = isolve==2 & xlength(:) <= 14;
etas(idx,:) = repmat([0 1],sum(idx),1);
toc
Amir Torabi
Amir Torabi 2019 年 12 月 2 日
very grateful. It really works great!.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by