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

60 views (last 30 days)
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 Comments
mohammed
mohammed on 19 Feb 2014
Edited: mohammed on 19 Feb 2014
Dear Alex
can you show your desired output?
like you want 5 matrix or only one Matrix.
Danilo NASCIMENTO
Danilo NASCIMENTO on 19 Feb 2014
Edited: Danilo NASCIMENTO on 19 Feb 2014
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.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 19 Feb 2014
Edited: Star Strider on 19 Feb 2014
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

More Answers (2)

mohammed
mohammed on 19 Feb 2014
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 Comment
Alex
Alex on 20 Feb 2014
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.

Sign in to comment.


Roger Stafford
Roger Stafford on 20 Feb 2014
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));

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!