Matrix indexing using a vector

2 次查看(过去 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