Borrar filtros
Borrar filtros

Creating peculiar vectors and matrices of ones and zeros

1 visualización (últimos 30 días)
John Kim
John Kim el 18 de Oct. de 2016
Editada: Walter Roberson el 18 de Oct. de 2016
Dear all,
I have a vector of indices, e.g., i = [2, 3, 5].
1. How do I create a vector of length 10, say, v s.t. x = 1 for indices in i, 0 otherwise. Obviously, I can write
x = zeros(10,1); x(i) = 1;
but is there a one liner?
2. How do I create a diagonal matrix of size 10, say, M, s.t. M(k,k) = 1 if k is in i, 0 otherwise. Obviously, I can write
x = zeros(10,1); x(i) = 1; M = diag(x);
but is there a one liner?
I'd appreciate any and all help. Thanks so much!
Best,
John

Respuestas (1)

Walter Roberson
Walter Roberson el 18 de Oct. de 2016
Editada: Walter Roberson el 18 de Oct. de 2016
ismember(1:10, i)
diag(ismember(1:10,k))
If you were going larger, then you could
sparse(i, i, 1, N, N)
Where N was the size of matrix to use

Categorías

Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by