vector to upper and lower triangular matrix
28 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Edwin Chamba
le 10 Nov 2019
Commenté : Edwin Chamba
le 10 Nov 2019
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;
0 commentaires
Réponse acceptée
John D'Errico
le 10 Nov 2019
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
Plus de réponses (1)
David Hill
le 10 Nov 2019
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));
Voir également
Catégories
En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!