How to change a column vector into a square a matrix?
Show older comments
I am trying to change a column vector
p=[1;3;5]
into a square matrix P=[1,3;3,5]
Howevery I only manage to change the column vector p into a square matrix with element [1,0;3,5]
with the following code
p=[1;3;5]
n=2
P = zeros(n);
P(triu(ones(n)) == 1) = p;
P
8 Comments
Rik
on 16 May 2020
How do you determine what value should be used for the empty position?
Muhammad Prasetyo
on 16 May 2020
KSSV
on 16 May 2020
Yoy always deal with size 1*3?
Rik
on 16 May 2020
And what would you do for 5 elements?
Muhammad Prasetyo
on 16 May 2020
John D'Errico
on 16 May 2020
Edited: John D'Errico
on 16 May 2020
The example for a 3x3 matrix is not a vector of length 10. You only gave 6 elements there.
It LOOKS like you want to make a square matrix from a vector that has only the lower triangle, IF you are willing to assume the matrix is a SYMMETRIC matrix. Is THAT your goal?
In that case, your vector must ALWAYS contain a "triangle number" of elements. A triangle number is a number of the form n*(n+1)/2, where n would be the size of the matrix in equation.
Is this what you are asking? To create a symmetric matrix from only the lower triangle of that matrix, when it is stored ina vector? Must you write code for any size matrix?
And, finally, is this your homework assignment?
Muhammad Prasetyo
on 16 May 2020
Muhammad Prasetyo
on 16 May 2020
Accepted Answer
More Answers (2)
Fabio Freschi
on 16 May 2020
Not as elegant as it could be but it works, especially for small matrices
% matrix dimension
n = 3;
% your entries (here dummy values)
p = rand(n*(n+1)/2,1);
% get the indices of the position into the matrix. I understand it is the triangular upper part
[ir,jc] = find(triu(ones(n)));
% create the upper triangular matrix
Pup = accumarray([ir,jc],p,[n,n]);
% now make the symmetric matrix
P = (Pup+Pup.').*.5*eye(n)
Mehmed Saad
on 16 May 2020
Here is one with for loop
function P = Using_for_loop(p,n)
P = zeros(n);
[I,J]=ind2sub(size(P),1:numel(P));
for ii =1:n
sz = length(P(I==ii & J>ii-1));
P(I==ii & J>ii-1) = p(1:sz);
P(J==ii & I>ii-1) = p(1:sz);
p(1:sz) = [];
end
end
Now call it
p = [11;12;13;14;22;23;24;33;34;44];
n = 4;
P = Using_for_loop(p,n)
P =
11 12 13 14
12 22 23 24
13 23 33 34
14 24 34 44
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!