フィルターのクリア

Creating peculiar vectors and matrices of ones and zeros

1 回表示 (過去 30 日間)
John Kim
John Kim 2016 年 10 月 18 日
編集済み: Walter Roberson 2016 年 10 月 18 日
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

回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 10 月 18 日
編集済み: Walter Roberson 2016 年 10 月 18 日
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

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by