Filter löschen
Filter löschen

How to unvec a vector to get the original matrix ?

12 Ansichten (letzte 30 Tage)
Tuong
Tuong am 22 Jul. 2024
Kommentiert: Tuong am 23 Jul. 2024
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 !

Akzeptierte Antwort

Dheeraj
Dheeraj am 22 Jul. 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 Kommentare
John D'Errico
John D'Errico am 22 Jul. 2024
Bearbeitet: John D'Errico am 22 Jul. 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.
Tuong
Tuong am 23 Jul. 2024
Thank you so much !

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by