Selecting Elements of a Matrix by Indexing with a Vector

조회 수: 3 (최근 30일)
Darren Wethington
Darren Wethington 2020년 4월 23일
댓글: Ameer Hamza 2020년 4월 23일
I have a 100x3 matrix and I'd like to select one element from each row to form a 100x1 vector. Given a vector of 100 indeces between 1-3, how can I obtain this? The code below is what I thought should work, but instead produces a 100x100 matrix (concatenation of each 100x1 vector generated by each value of indx).
A = rand(100,3);
indx = randi([1 3],100,1); % for each row, which column do I want to pull the element from?
B = A(:,indx); % B is 100x100, I want 100x1

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 4월 23일
편집: Ameer Hamza 2020년 4월 23일
See sub2ind() function.
A = rand(100,3);
indx = randi([1 3],100,1);
idx = sub2ind(size(A), (1:size(A,1)).', indx);
B = A(idx);
  댓글 수: 2
Darren Wethington
Darren Wethington 2020년 4월 23일
This worked, I was just hoping to not have to sub2ind it and was curious if there was a more straightforward way. I'll use this, thanks.
Ameer Hamza
Ameer Hamza 2020년 4월 23일
I think sub2ind is the simplest way to do such a thing. Following avoids sub2ind, but I am not sure you can call it straightforward
A = rand(100,3);
indx = randi([1 3],100,1);
ind = (1:size(A,1)).' + (indx-1).*size(A,1);
B = A(ind);

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

추가 답변 (1개)

David Hill
David Hill 2020년 4월 23일
A = rand(100,3);
indx = randi([1 3],100,1);
B = A(1:100,indx);

카테고리

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