Vectorized implementation for using a vector as an index for matrices

1 visualización (últimos 30 días)
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

Respuesta aceptada

Stephen23
Stephen23 el 3 de Dic. de 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
>>

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by