Vectorization in more than two dimensions

조회 수: 4 (최근 30일)
Nicole Brimhall
Nicole Brimhall 2020년 11월 25일
댓글: Nicole Brimhall 2020년 11월 25일
Is there a way to use vectorized operations in more than two dimensions? For example, in the following code I want to create a three-dimensional matrix based off a function in three variables. I am able to vectorize in two dimensions using the transpose function, but for the third dimension I use a for loop. Is there a way to eliminate the loop?
x=1:1000;x=x';
y=1:586;
z=1:247;
U=zeros(length(x),length(y),length(z));
for cnt=1:length(z)
U(:,:,cnt)=(x.^2+y.^3*z(cnt)).*exp(x*z(cnt).^2).*besselj(0,y);
end
  댓글 수: 1
Nicole Brimhall
Nicole Brimhall 2020년 11월 25일
I think I figured out a solution. If there is a more elegant way, I am all ears. I want to extend this to five dimensions, and keeping track of the permutations is going to be tricky.
x=1:5;
y=1:6;
z=1:3;
X=repmat(x',[1 length(y) length(z)]);
Y=repmat(y,[length(x) 1 length(z)]);
Z=repmat(z,[length(x) 1 length(y)]);Z=permute(Z,[1 3 2]);
U=(X.^2+Y.^3.*Z).*exp(X.*Z.^2).*besselj(0,y);

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

답변 (1개)

Walter Roberson
Walter Roberson 2020년 11월 25일
편집: Walter Roberson 2020년 11월 25일
X = reshape(1:5, [], 1, 1);
Y = reshape(1:6, 1, [], 1);
Z = reshape(1:3, 1, 1, []);
U = (X.^2+Y.^3.*Z).*exp(X.*Z.^2).*besselj(0,Y);
size(U)
ans = 1×3
5 6 3
Need R2016b or later.
  댓글 수: 2
Jan
Jan 2020년 11월 25일
This is much more efficient then expanding the arrays. besselj is expensive. Then expanding the argument wastes a lot of time with calculating the results for the same inputs.
Nicole Brimhall
Nicole Brimhall 2020년 11월 25일
Thank you. That was very helpful.

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by