Usage of ndgrid for multidimensional arrays

2 views (last 30 days)
Hi
I have following two matrices:
A = rand(3,180); B = rand(500,1);
I want to use them so that at the end, I have output of besselj function:
Output = besselj(x,y); where x's comes from B, and y comes from the row data of A.
Here, my output is 3-D. It is 500x180x3. The last "3" stands for the different rows of A. It seems very complicated. How can I do that?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 7 Jul 2014
Edited: Andrei Bobrov on 7 Jul 2014
Output = zeros(500,180,3);
A1 = reshape(A,1,size(A,2),[]);
for ii = 1:numel(B)
Output(ii,:,:) = besselj(B(ii),A1);
end
other way
x = repmat(B(:),[1 fliplr(size(A))]);
y = repmat(permute(A,[3 2 1]),numel(B),1);
Output = besselj(x,y);
or
Output = bsxfun(@(x,y)besselj(x,y),B(:),repmat(permute(A,[3 2 1]),numel(B),1));
and with ndgrid:
s = size(A);
[ii,jj,k] = ndgrid(B,1:s(2),1:s(1));
Output = besselj(ii,A(sub2ind(s,k,jj)));

More Answers (0)

Community Treasure Hunt

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

Start Hunting!