Matrix Indexing from an Array of Numbers

조회 수: 2 (최근 30일)
Lauren Hopkins
Lauren Hopkins 2016년 2월 26일
댓글: Lauren Hopkins 2016년 2월 26일
Hello:
I have a matrix Y = 55x236 of values and a separate matrix Z = [24 38 46 52 66] I would like to extract all of the rows of Y but ONLY the columns starting at the values in Z (plus the next 4 columns). So in other words I would like to extract from Y, columns 24-28, 38-42, 46-50, 52-56, and 66-70.
So far I have been doing this with a for loop but this seems like something that could be done much easier. I have tried something like A = Y(:, (Z:Z+4)) but this only gives me columns 24-28. If I have to index into Z to do this, wouldn't that still require a loop?

채택된 답변

Roger Stafford
Roger Stafford 2016년 2월 26일
편집: Roger Stafford 2016년 2월 26일
Assuming Z is a row vector
Y2 = Y(:,bsxfun(@plus,Z,(0:4).'));
  댓글 수: 1
Lauren Hopkins
Lauren Hopkins 2016년 2월 26일
Perfectly elegant; thanks. Also introduced me to bsxfun which I'm definitely going to use a lot in the future. Cheers!

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

추가 답변 (1개)

dpb
dpb 2016년 2월 26일
One soluion; may be some "more better"...
idx=cell2mat(arrayfun(@colon,Z,Z+4,'uniform',0))); % column indices vector
A=Y(:,idx);
On can dispense with the temporary idx of course by folding into the indexing expression...
  댓글 수: 1
Lauren Hopkins
Lauren Hopkins 2016년 2월 26일
This in-and-of itself is very interesting as I wasn't sure there was a 'one-line' piece of code that could extend the indices into ranges. And it certainly does the job. Thank you for your response!

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by