Convert a vector to a matrix in MATLAB. How can I do this?

3 views (last 30 days)
I have this vectroe A=[1 2 3 4 5 6] and i wanto to convert it to this matrix B=[0 1 2 3 4;1 0 4 5;2 4 0 6;3 5 6 0].How can I do?
B =
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0

Answers (1)

Arjun
Arjun on 5 Feb 2025
On careful observation of matrix 'B', it can be observed that it is a symmetric matrix i.e B = B'(B Transpose). You can efficeintly fill this matrix 'B' using the entries of matrix 'A' by filling only the upper triangle of 'B' and then simply adding the transpose of upper triangle back to it to get the full matrix. Since this is only a 4x4 matrix even manual filling would not be troublesome but if the dimensions were higher that could have been a challenge.
You can run nested 'for' loops to fill the upper triangle of the matrix by subsequent entries from the matrix 'A'.
You can refer to the code below for more details:
A = [1 2 3 4 5 6];
nmax = 4; % Dimensions of matrix B
B = zeros(nmax);
% pos will point to the next element of A to put inside B
pos = 1;
% Nested for loops to fill the upper triangle
for i = 1:nmax-1
for j= i+1:nmax
B(i,j) = A(pos);
pos = pos+1;
end
end
% Adding transpose of B to itself to generate full matrix
B = B + B';
disp(B)
0 1 2 3 1 0 4 5 2 4 0 6 3 5 6 0
You can refer to the documentation of 'for' loops for more details: https://www.mathworks.com/help/releases/R2021a
I hope this helps!

Community Treasure Hunt

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

Start Hunting!