Home > Software design >  Combine and sort data based on indices in Matlab
Combine and sort data based on indices in Matlab

Time:08-18

I have 2 datasets like this

dataset1 (31x1 double):

0
32
45
8
...
91

dataset2 (40x1 double):

5
12
27
10
...
15

I also have dataset1_index (31x1 double) that indexes the values of datset1 from a larger dataset

2
5
6
9
...
58

Similarly, I have dataset2_index (40x1 double) that indexes the values of datset2 from the same larger dataset

3
7
8
13
...
62

I would like to combine dataset1 and dataset2 into dataset3 (71x1 double) but the order of values in dataset3 should follow the order (from small to large) of dataset1_index and dataset2_index. Could anyone help?

CodePudding user response:

You could create a 71x2 matrix containing the indices and values, then sortrows() on the index column, and take the sorted values column

B = sortrows(A,column) sorts A based on the columns specified in the vector column. For example, sortrows(A,4) sorts the rows of A in ascending order based on the elements in the fourth column

dataset1 = [0
32
45
8];

dataset2 = [5
12
27
10];

dataset1_index = [2
5
6
9];

dataset2_index = [3
7
8
13];

tmp = sortrows([dataset1_index dataset1; dataset2_index dataset2], 1);

%    2    0
%    3    5
%    5   32
%    6   45
%    7   12
%    8   27
%    9    8
%   13   10


dataset3 = tmp(:, 2);
dataset3_index = tmp(:, 1);
  • Related