I have a matrix which size is mxm (square) variable and I wanna assign a mx1 matrix into the first matrix's diagonal. What kind of loop I have to write?

for example;
%m=matrix's row which is variable depends on the input
a=zeros(m)
b=[mx1]
I wanna assign b matrix into the a matrix's diagonal.

댓글 수: 3

Give a small example, and tell what should be the result
a=[0 0 0;0 0 0;0 0 0]
b=[1 2 3]
c=[1 0 0;0 2 0;0 0 3] I wanna create c matrix which its diagonal belongs to b
I was going to suggest the cyclist's third method, which he posted before your comment above. Did you try it?

댓글을 달려면 로그인하십시오.

 채택된 답변

the cyclist
the cyclist 2013년 5월 19일
편집: the cyclist 2013년 5월 19일
This is very easy, if the off-diagonal element are always zeros:
m = 5;
b = rand(m,1);
a = diag(b);
But if you want a more general way to insert b along the diagonal of any array a, then here's one way:
m = 5;
% Set up the array and vector:
a = magic(m);
b = rand(m,1);
% Insert vector into main diagonal of array
a(1:m+1:end) = b;
Another way to do the last step is:
a(logical(eye(m))) = b;

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2013년 5월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by