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

60 次查看(过去 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 个评论
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