Defining a function (including vector dot product) for all the points in 3D

조회 수: 4 (최근 30일)
AP
AP 2014년 6월 3일
댓글: Matt J 2014년 6월 3일
I am trying to build the following function in a three dimensional domain.
where k is a constant vector, X is the position vector, c is a constant number, and t is time.
k is a vector of size [1 3], X is an array of size [NX*NY*NZ 3] that represents the points in the three-dimensional domain, c is a constant, and t is an array of size [1 NT].
The following is the setup of the problem.
dx = 0.1;
dy = 0.5;
dz = 0.1;
[x, y, z] = meshgrid( (1:100)*dx, (1:100)*dy, (1:100)*dz );
X = [x(:) y(:) z(:)];
k = [1 2 3];
c = 0.5;
t = 0:0.1:1;
I thought about using arrayfun and repeating the vector k using repmat and dot it with X in the second dimension but I don't know what I should do for the multiplication of c and t.
In fact, the following loop works but it is very slow (takes 200 seconds on my machine).
f = zeros(numel(X)/3, numel(t));
for n = 1:numel(t)
for i = 1:numel(X)/3
f(i, n) = tan(dot(k, X(i,:)+c*t(n)));
end
end
What would be an efficient way of defining the function for all the points and all the times? The output of this function, for example, looks like an array of size [NX*NY*NZ NT].

채택된 답변

Matt J
Matt J 2014년 6월 3일
f = tan( bsxfun(@plus, X*k(:), c*t) );
  댓글 수: 3
Matt J
Matt J 2014년 6월 3일
편집: Matt J 2014년 6월 3일
X*k(:) computes all the dot(X(i,:),k)'s
For column vector u and row vector v,
Y=bsxfun(@plus, u,v)
computes a matrix Y with Y(i,j)=u(i)+v(j). See "doc bsxfun".
Matt J
Matt J 2014년 6월 3일
This is probably a bit faster
k = [1 2 3];
c = 0.5;
t = 0:0.1:1;
[x, y, z] = meshgrid( (1:100)*(k(1)*dx),
(1:100)*(k(2)*dy),
(1:100)*(k(3)*dz);
f=tan( bsxfun(@plus, x(:)+y(:)+z(:), ct) );

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

George Papazafeiropoulos
George Papazafeiropoulos 2014년 6월 3일
편집: George Papazafeiropoulos 2014년 6월 3일
% data
dx = 0.1;
dy = 0.5;
dz = 0.1;
[x, y, z] = meshgrid( (1:100)*dx, (1:100)*dy, (1:100)*dz );
X = [x(:) y(:) z(:)];
k = [1 2 3];
c = 0.5;
t = 0:0.1:1;
lt=length(t);
% engine
u=numel(X)/3;
t=t(ones(u,1),:);
X=repmat(X,lt,1);
t=t(:);
t=t(:,ones(1,3));
u1=sum(k(ones(numel(X)/3,1),:).*(X+c*t),2);
ff=tan(u1);
% result
ff=reshape(ff,u,[])

카테고리

Help CenterFile Exchange에서 Lighting, Transparency, and Shading에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by