removing for loop by using 3d matrix
3 ビュー (過去 30 日間)
古いコメントを表示
Hi. I wrote a code. I want to calculate pressure(p) of waves which produces by 1d array of elements. p is 2d variable. In the code I used 2d matrix and 2 loop. now I want to make a 3d matrix to remove one of the loops. but the problem that I have is when I creat 3d matrix p also gets a 3d matrix while it must be a 2d matrix.
clc;
close all;
clear all;
a=1;
c=1.5; % mm/us
T=5; dt=0.8; % us
fc=1;BW=3; % MHz
R=10;
xf=20;zf=20;
td=0;
dx=0.3; dz=0.3;pitch=0.3;
% x0=10; z0=0;
f=@(x) exp(-x.^2*BW^2);
g=@(x) sin(2*pi*fc*x);
H=@(x) f(x).*g(x);
Nz=120;
Nx=120;
x=[1:Nx]*dx;
z=[1:Nz]*dz;
xl=[1:Nx]*dx;
[z3,x3,xxl] = ndgrid(z,x,xl);
for t=0:dt:T
d3=sqrt((x3-xxl).^2+(z3).^2);
df=sqrt((xxl-xf).^2+(zf)^2);
td=(R-df)./c;
tt_hat=(d3./c)+td;
p = 1./sqrt(d3).*H(t-tt_hat); %
imagesc(p(:,:,100));
% colormap gray; colorbar;
% set(gca,'clim');
% title(['Time= ',num2str(t)]);
pause(0.05);
end
3 件のコメント
回答 (1 件)
Jan
2021 年 2 月 16 日
編集済み: Jan
2021 年 2 月 18 日
What is your purpose of vectorizing the code? The processing time is dominated by imagesc and pause here. I assume the loop are faster than the vectorizde code, which produces large intermediate arrays. Your original loop takes 0.86 seconds, the code in the comment above 1.33 seconds, if imagesc and pause are removed.
You can add an additional dimension:
dim = [1, size(tt_hat)];
p = H((0:dt:T).' - reshape(tt_hat, dim)) ./ reshape(sqrt(d3), dim);
p1 = sum(p, 4).^2;
But I do not see the advantage compared to clean loops.
If efficiency matters, remember that anonymous functions are expensive. So reduce them to the minimum:
% This:
f=@(x) exp(-x.^2*BW^2);
g=@(x) sin(2*pi*fc*x);
H=@(x) f(x).*g(x);
% slows down the total processing time by 10% compare to this:
H = @(x) exp(-x.^2 * BW^2) .* sin(2 * pi * fc * x);
Note: Please format your code in the forum to improve the readability. I've done this for you today.
The brute clearing header "clc;close all;clear all;" is extremly inefficient: the clear('all') removes all functions from the memory and forces Matlab to reload them from the slow disk. This wastes a lot of time and offers no advantage. Prefer using functions instead to keep your workspace clean.
4 件のコメント
Jan
2021 年 2 月 19 日
Hi. This code produces a 3D array. Of course it does, because the original code produces a set of 2D arrays. Concatenating a bunch of 2D matrices must create a 3D array.
Why do you want to get a 2D matrix? What should happen with the additional information?
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!