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
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
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
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.
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 Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!