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!