Convert a vector to a matrix in MATLAB. How can I do this?
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Arjun
2025-2-5
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)
You can refer to the documentation of 'for' loops for more details: https://www.mathworks.com/help/releases/R2021a
I hope this helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!