필터 지우기
필터 지우기

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 CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by