필터 지우기
필터 지우기

Is there any way to assign a value to the diagonals of a matrix (not just the main diagonal)?

조회 수: 39 (최근 30일)
I have a vector of values that I want to assign to the diagonals of a matrix. So for example, if my vector is
v = [ 2 7 8 9 5];
I want to make a matrix to have all the elements of the 1st diagonal equal to v(1), all the elements of the second diagonal equal to v(2), all of the elements of the third (and main) diagonal equal to v(8), and so on.
Is there any way to do that?
  댓글 수: 2
mohammed
mohammed 2014년 2월 19일
편집: mohammed 2014년 2월 19일
Dear Alex
can you show your desired output?
like you want 5 matrix or only one Matrix.
Danilo NASCIMENTO
Danilo NASCIMENTO 2014년 2월 19일
편집: Danilo NASCIMENTO 2014년 2월 19일
Let me understand... The order of your matrix should the length of your v vector... Is that what you mean? Actually I don't know what are you trying to perform... But this way you will not fill the matrix completely, the extremes of the inverse main diagonal will be left blank.

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

채택된 답변

Star Strider
Star Strider 2014년 2월 19일
편집: Star Strider 2014년 2월 19일
There is no ‘ v(8) ’. I assume you mean v(3) = 8.
This looks so kludgy that I’m almost ashamed to post it, but if I understand your question, it does what you want:
v = [ 2 7 8 9 5]
vc = size(v,2);
M = zeros(round(vc/2));
for k1 = 1:vc
rvc2 = round(vc/2);
if k1 <= rvc2
Mi = diag(ones(1,k1)*v(k1), rvc2-k1);
elseif k1 > rvc2
Mi = diag(ones(1,abs(rvc2+1-round(k1/2)))*v(k1), rvc2-k1);
end
M = M + Mi;
end
The matrix it produces is:
M =
8.0000e+000 7.0000e+000 2.0000e+000
9.0000e+000 8.0000e+000 7.0000e+000
5.0000e+000 9.0000e+000 8.0000e+000

추가 답변 (2개)

mohammed
mohammed 2014년 2월 19일
Dear Alex
v = [ 2 7 8 9 5];
for i = 1:length(v)
b{i} = eye(3)*v(i)% 3 is the size of identity Matrix
end
i hope it will help you.
  댓글 수: 1
Alex
Alex 2014년 2월 20일
Hi, thanks for your answer! I actually wanted them all in one matrix, but I did not specify that previously. I am sorry for that, and I thank you for your help all the same.

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


Roger Stafford
Roger Stafford 2014년 2월 20일
It depends on which side you call the "first" diagonal. If you use the order sense of matlab's 'diag' function, the diagonal numbers increase from lower left to upper right, so the first diagonal would be on the lower left. With definition do:
M = toeplitz(v(3:-1:1),v(3:5));
If you order them in the opposite direction, do:
M = toeplitz(v(3:5),v(3:-1:1));

카테고리

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