Create a double identity matrix matlab
조회 수: 2 (최근 30일)
이전 댓글 표시
If we have an identity matrix of dimensions (M*M) we use:
M=12;
K=eye(M);
But how can we obtain this matrix in general way: (it means double the identity)
K =
1 0 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0 0
0 0 0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0
0 0 0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 0 1 1
댓글 수: 0
채택된 답변
John D'Errico
2022년 3월 11일
편집: John D'Errico
2022년 3월 11일
There are many basic ways, some not so basic. Perhaps my favorite is just:
n = 8;
A = triu(tril(ones(n)),-1)
Here is another easy one:
A = eye(n) + diag(ones(n-1,1),-1)
And yet another cute one is:
A = toeplitz([1 1,zeros(1,n-2)],[1,zeros(1,n-1)])
Oh, wait. This next one is just too pretty to disregard:
flip(hankel([zeros(1,n-2),1 1]))
Of course, if n is seriously large, then you would want to create the result as a sparse matrix. Now spdiags is clearly a great solution.
n = 30;
A = spdiags(ones(n,2),[-1,0],n,n);
spy(A)
Actually, 30 is not at all large in context, but I made n only 30 so you could see that it worked. For a sparse matrix to be truly valuable, I'd only worry about it if n was on the order of 1000 or more.
The trick to solving such a problem in MATLAB is to get used to understanding how the various matrix tools can be used, and some experience in seeing how elements are stored in matrices. That helps you to see the many possible solutions to such a problem. Already in my mind I can see at least one other fairly simple solution. No, two more, at least. I could use meshgrid, maybe use indexing, or god forbid, a loop. Nah, skip the loop. Other ways should be there too.
댓글 수: 0
추가 답변 (3개)
Ive J
2022년 3월 11일
Maybe not the best way, but works:
% taken from doc kron
n = 12;
I = speye(n, n);
E = sparse(2:n, 1:n-1, 1, n, n);
K = full(I + E)
댓글 수: 0
Sugar Daddy
2022년 3월 11일
Daddy is here for help
M = 12;
K = transpose(eye(M)+triu(circshift(eye(M),1,2)))
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!