Finding highest position of values in two arrays?
3 views (last 30 days)
Show older comments
Hello,
i have two matrices with two columns. I want to sort them after one column. After it this matrices should compare one column. For example after the sort of the first row the first row of A should be compared with the first row of B. In this both rows are the same numbers, but in different sequence. The highest number in both of this rows should be copied to a matrix C(1,1). The date from the second row of A to C(2,1) and from B to C(3,1). This should be done for all members of the A matrix.
How could the code look like?
0 Comments
Answers (3)
Rik
on 21 Jul 2018
Edited: Rik
on 23 Jul 2018
Update: the code below incorporates what you describe and results in the required C.
A=[0.1 3;0.3 1;0.6 2];B=[0.7 2; 0.8 3; 0.9 1];
%first, sort by ID, which makes everything easier
A = sortrows(A, 2);
B = sortrows(B, 2);
%next, find the rank for each ID
[~,rankA]=sort(A(:,1),'descend');
[~,rankB]=sort(B(:,1),'ascend');
%calculate the cost and sort it to get the overall ranking
costFcn=rankA/(numel(rankA)-0.1)+rankB/numel(rankB);
[~,rankC]=sort(costFcn);
%create C
C=[rankC A(rankC,1) B(rankC,1)];
original post:
Something like this?
dummy_A=rand(10,2);
dummy_B=rand(10,2);
[~,order]=sort(dummy_A(:,1));
A=dummy_A(order,:);
[~,order]=sort(dummy_B(:,1));
B=dummy_B(order,:);
C=[max([A B],[],2) A(:,2) B(:,2)];
If this is not what you mean, please provide some way to generate plausible data and a sample output.
15 Comments
Michael Simonovski
on 23 Jul 2018
3 Comments
Rik
on 27 Jul 2018
I'm on mobile, so I can't test my code with this input, but it should yield the correct result. Does it? Otherwise I would suggest using Guillaume's answer.
Guillaume
on 24 Jul 2018
I don't really understand your description of the rule to figure out the ordering. Whatever it is however, it should be trivial to implement.
I would recommend that you switch to using tables, it would allow you to trivially merge your two arrays and sort the result according to whichever rule you want. In addition, it makes clear what each column represent and also makes whatever calculation you want to perform easier to understand
A=[0.1,2;0.6,9;0.7,10;0.4,6;0.8,3;0.9,1];
B=[0.3,1;0.8,10;0.6,3;0.9,6;0.22,9;0.82,2];
%convert arrays to tables
tA = array2table(A, 'VariableNames', {'Friction', 'ID'});
tB = array2table(B, 'VariableNames', {'Force', 'ID'});
%merge tables
tmerged = join(tA, tB)
%create a cost function. Use whatever formula you want
tmerged.Cost = tmerged.Force + tMerged.Friction %e.g sum of force and friction
%sort first according to cost, then if equal according to force, then friction
tsorted = sortrows(tmerged, {'Cost', 'Force', 'Friction'})
0 Comments
See Also
Categories
Find more on Matrices and Arrays 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!