How to unvec a vector to get the original matrix ?

11 visualizzazioni (ultimi 30 giorni)
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 !

Risposta accettata

Dheeraj
Dheeraj il 22 Lug 2024
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 Commenti
John D'Errico
John D'Errico il 22 Lug 2024
Modificato: John D'Errico il 22 Lug 2024
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.

Accedi per commentare.

Più risposte (0)

Tag

Prodotti


Release

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by