How to reshape matrix according to the given matrix?

조회 수: 1 (최근 30일)
SANDEEP SINGH RANA
SANDEEP SINGH RANA 2021년 12월 31일
편집: Cris LaPierre 2022년 1월 3일
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

채택된 답변

Cris LaPierre
Cris LaPierre 2021년 12월 31일
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
SANDEEP SINGH RANA
SANDEEP SINGH RANA 2022년 1월 3일
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 2022년 1월 3일
편집: Cris LaPierre 2022년 1월 3일
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

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

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by