vector to upper and lower triangular matrix

35 ビュー (過去 30 日間)
Edwin Chamba
Edwin Chamba 2019 年 11 月 10 日
コメント済み: Edwin Chamba 2019 年 11 月 10 日
Hey, I'm new to Matlab and wanted to know how to input a 1 by n matrix and output a n by n matrix such that the diagonals are the mean of the 1 by n matrix and the upper and lower trianglars are elements of that 1 by n matrix. I have it working for the case n = 3 and here is my code:
A = [ 5 4 3];
a = [0 A(1) A(2);
A(1) 0 A(3);
A(2) A(3) 0];
A_ij = mean(A)*eye(length(A),length(A)) + a;impendence.PNG

採用された回答

John D'Errico
John D'Errico 2019 年 11 月 10 日
What you fail to see is that while your code works for a 3x3 matrrix, it must always fail for any n other than n==3.
You want to provide a vector of length n, and use it to populate the upper and lower triangles of the matrix, as you did for the 3x3.
What about n==2? That would suggest you would supply a vector of length 2. But there is only ONE element in the upper or lower triangle of a 2x2 matrix.
How about if n is other than 3? Note that in general, there are n*(n-1)/2 elements in the upper triangle of an nxn matrix. When n==3, we get exactly 3 elements in the triangles. But consider this little table:
[n;n.*(n-1)/2]
ans =
1 2 3 4 5
0 1 3 6 10
The first row is n. The second row is the number of elements in the strict upper triangle of an nxn matrix (as well as the strict lower triangle.)
The point being that you CANNOT supply a vector of length n and hope to get the result that you are asking for. It just won't work, ever, except for n==3. So for a 5x5 matrix, there are 10 elements in that upper triangle.
If you supply the correct number of elements, then yes, you can easily build a matrix. I'll give you one solution, perhaps with this:
n = 5;
V = 1:10;
ind = find(tril(ones(n,n),-1));
LT = zeros(n);
LT(ind) = V;
LT
LT =
0 0 0 0 0
1 0 0 0 0
2 5 0 0 0
3 6 8 0 0
4 7 9 10 0
MAT = LT + LT' + eye(n)*mean(V)
MAT =
5.5 1 2 3 4
1 5.5 5 6 7
2 5 5.5 8 9
3 6 8 5.5 10
4 7 9 10 5.5
  1 件のコメント
Edwin Chamba
Edwin Chamba 2019 年 11 月 10 日
Thank you for the clarification

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

その他の回答 (1 件)

David Hill
David Hill 2019 年 11 月 10 日
Not sure what elements you want above and below the diagonal.
a=repmat(A,[length(A),1]).*~diag(ones(1,length(A)))+mean(A)*eye(length(A));
  1 件のコメント
Edwin Chamba
Edwin Chamba 2019 年 11 月 10 日
Thank you for the code. I added a picture to try to better explain what I meant by the above and below parts of the diagonals.

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

カテゴリ

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