Vectorized implementation for using a vector as an index for matrices

조회 수: 1 (최근 30일)
Hello, I have a culumn vector V of m numbers from 1 to 10.
I would like to crate a m x 10 matrix A where in each line i, the V(i) th element is set to 1 and rest to 0.
here's an example of the code I'm trying to vectorize :
A = zeros(m,10);
for i=1:m
A(v(i))=1;
end

채택된 답변

Stephen23
Stephen23 2019년 12월 3일
Use sub2ind like this:
>> m = 7;
>> V = randi([1,10],1,m)
V =
9 10 2 10 7 1 3
>> A = zeros(m,10);
>> A(sub2ind(size(A),1:m,V)) = 1
A =
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
>>

추가 답변 (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