Vectorized implementation for using a vector as an index for matrices

1 view (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 3 Dec 2019
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
>>

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!