Effacer les filtres
Effacer les filtres

Creating peculiar vectors and matrices of ones and zeros

1 vue (au cours des 30 derniers jours)
John Kim
John Kim le 18 Oct 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

Réponses (1)

Walter Roberson
Walter Roberson le 18 Oct 2016
Modifié(e) : Walter Roberson le 18 Oct 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

Catégories

En savoir plus sur Operating on Diagonal 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