필터 지우기
필터 지우기

how to use bsxfun or arrayfun to build the following matrix

조회 수: 2 (최근 30일)
Jason
Jason 2016년 2월 25일
편집: Walter Roberson 2016년 2월 25일
Hi, there.
I want to use bsxfun or arrayfun to replace the following for loop.
for s=1:S
New_P(s,:)=P(s,:,U0(s));
end;
for example,
if P(,,1)=[1,2;3,4];
P(:,:,2)=[5,6;7,8];
U0=[1;2];
then the final result is New_P=[1,2;7,8];
Thank you in advance!
  댓글 수: 2
Adam
Adam 2016년 2월 25일
Is there any particular reason why you want to use arrayfun or bsxfun? arrayfun is generally slower than a for loop and is also more suited to 1d arrays than multidimensional arrays. It can certainly be used for multidimensional arrays, but it effectively just interprets it as a 1d array anyway using linear indexing on the array.
I'm not aware of a syntax of bsxfun that would be useful for this, though maybe it is. I use it for certain specific tasks so haven't used all its capabilities.
Jason
Jason 2016년 2월 25일
thank you for your comments. because when the size of the matrix is very large, the for loop is generally very unefficiency, so i want use a vectorized expression.

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

채택된 답변

Guillaume
Guillaume 2016년 2월 25일
Neither arrayfun nor bsxfun are useful for this. sub2ind is:
P = cat(3, [1 2;3 4], [5 6;7 8]);
U0 = [1;2];
New_P = P(sub2ind(size(P), ...
repmat((1:size(P, 1))', 1, size(P, 2)), ... rows where to pick the elements
repmat(1:size(P, 2), size(P, 1), 1), ... columns where to pick the elements
repmat(U0, 1, size(P, 2)))) %pages where to pick the elements
  댓글 수: 1
Guillaume
Guillaume 2016년 2월 25일
Note that you could generate the rows and columns matrix with ngrid if you prefer:
[rows, cols] = ndgrid(1:size(P, 1), 1:size(P, 2));
new_P = P(sub2ind(size(P), rows, cols, repmat(U0, 1, size(P, 2))))

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by