Vectorized implementation for using a vector as an index for matrices

1 vue (au cours des 30 derniers jours)
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

Réponse acceptée

Stephen23
Stephen23 le 3 Déc 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
>>

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by