Matrix indexing using a vector

조회 수: 1 (최근 30일)
Fabio Pasquarella
Fabio Pasquarella 2016년 5월 30일
답변: Andrei Bobrov 2016년 5월 30일
Let's say I have a vector b where each row correspond to an index for each row in the matrix A. I want to assign 1 to these elements, like in the matrix C, without loops. Thank you
A = zeros(4,3);
b = [2;1;2;3];
C = [0 1 0; 1 0 0; 0 1 0; 0 0 1]

채택된 답변

Stephen23
Stephen23 2016년 5월 30일
편집: Stephen23 2016년 5월 30일
You can use sub2ind for this:
>> A = zeros(4,3);
>> col = [2;1;2;3];
>> row = 1:numel(col);
>> A(sub2ind(size(A),row(:),col(:))) = 1
A =
0 1 0
1 0 0
0 1 0
0 0 1

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2016년 5월 30일
C = accumarray([(1:numel(b))' b],1)

카테고리

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