How to unvec a vector to get the original matrix ?

조회 수: 11 (최근 30일)
Tuong
Tuong 2024년 7월 22일
댓글: Tuong 2024년 7월 23일
I know that I can just vectorize a matrix by using the ":" operator like this. For example
A = [1 2;3 4];
%B is vec of A
B = A(:)
This would lead to
Now suppose that I already have B in the first place, what would be the best Matlab practice to get back ?
Would you kindly help me with this ?
Thank you for your enthusiasm !

채택된 답변

Dheeraj
Dheeraj 2024년 7월 22일
Hi Tuong,
I understand you want to reshape a column vector to it's original matrix form.
To reshape a vector back into its original matrix form, you can use the "reshape" function in MATLAB. Given that you have a vector B and you know the dimensions of the original matrix, you can reshape B to get back the matrix.
For example, if you originally had a matrix A that was 2x2, you can reshape B to be 2x2 as follows:
A = [1 2; 3 4];
B = A(:); % B is now [1; 3; 2; 4]
% To reshape B back to its original form
originalRows = 2; % Number of rows in the original matrix
originalCols = 2; % Number of columns in the original matrix
A_reconstructed = reshape(B, originalRows, originalCols);
This way, you can get back the matrix A from its vectorized form B using the "reshape" function with the known dimensions of the original matrix. Please note that it is required to know the original dimensions of the matrix before vectorization to obtain the original matrix.
Thank you.
  댓글 수: 4
John D'Errico
John D'Errico 2024년 7월 22일
편집: John D'Errico 2024년 7월 22일
I once wrote a code that would try to infer what the original size of the matrix was, for some vector. For example, given a vector with 1147 elements...
n = 1147
n = 1147
d = divisors(n)
d = 1x4
1 31 37 1147
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
factorpairs = [d;n./d]
factorpairs = 2x4
1 31 37 1147 1147 37 31 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
And we see the array was either 31x37, or 37x31.
This was useful when working with images, when sometimes an image would get unrolled into a vector, and I wanted to recover the original image, but had forgotten the size. :( At least I would then have a guess at what the size could have been. Once you know what sizes were even possible, now you can test to see which ones made sense, since after reshaping the result, most of those potential reshaped image arrays would have looked random. A better solution was simply to know what size was the image I am working with.
Tuong
Tuong 2024년 7월 23일
Thank you so much !

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by