フィルターのクリア

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 件のコメント
Alex
Alex 2014 年 2 月 20 日
Thanks so much! That's exactly what I wanted!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by