How to reshape matrix according to the given matrix?

13 views (last 30 days)
Hi,
Let i have 10 X 1 matrix
matrix_value indices
1 - 3
2 - 5
3 - 2
4 - 1
5 - 2
6 - 4
7 - 5
8 -1
9 - 4
10 - 3
Now I have store this in matrix of size 5 x 2 such that matrix_value of same indices will be in pairs ( in this i have taken only pairs, it may be more) . Matrix_values will be like below:
row1 4 , 8
row2 3, 5
row3 1, 10
Hope you got this, I have to create loop so that next time when i will get 20 x 1 matrix with indices, I can arrange them in (10 x 2) or any ( * x 2) pair.
Thanks and Regards

Accepted Answer

Cris LaPierre
Cris LaPierre on 31 Dec 2021
I would use sort and reshape
% Original data
matrix_value = [3;5;2;1;2;4;5;1;4;3];
% sort the data
[tmp,I] = sort(matrix_value);
% reshape and transpose to be nx2
newInd = reshape(I,2,[])'
newInd = 5×2
4 8 3 5 1 10 6 9 2 7
newMat = reshape(tmp,2,[])'
newMat = 5×2
1 1 2 2 3 3 4 4 5 5
  4 Comments
SANDEEP SINGH RANA
SANDEEP SINGH RANA on 3 Jan 2022
Remaining empty column element can be replaced with zeros or initialized matrix using zeros(5,2), As below.
Matrix = 5×2
4 8
3 5
9 0
1 10
6 0
2 7
Only this I required is same indices matrix_value will be in pair of 2 column or it should be left alone.
Cris LaPierre
Cris LaPierre on 3 Jan 2022
Edited: Cris LaPierre on 3 Jan 2022
I guess the simplest approach would be to make sure all numbers appear an even number of times, then use the same approach as before. Set any indices greater than the length of the original vector to 0.
% original vector
matrix_value = [3;5;2;1;2;4;5;1;2;3];
% find number of times each value appears
[g,id] = groupsummary(matrix_value,matrix_value,"nnz")
g = 5×1
2 3 2 1 2
id = 5×1
1 2 3 4 5
% Append values to the bottom so all values appear an even number of times
odd = logical(rem(g,2));
matrix_value2 = [matrix_value;id(odd)];
% sort the data
[tmp,I] = sort(matrix_value2);
% reshape and transpose to be nx2
newInd = reshape(I,2,[])';
% set any indices greater than orginal length to 0
newInd(newInd>length(matrix_value)) = 0
newInd = 6×2
4 8 3 5 9 0 1 10 6 0 2 7

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!