Help required for sorting

5 views (last 30 days)
Amin Waqas
Amin Waqas on 12 Nov 2020
Commented: Amin Waqas on 13 Nov 2020
I have a table of size 17520X33 having multiple buyers' price and their required quantites.I want to arrange buyers based on price in desending order with ID. After arrange them in desending order i want to adjust their demand. Below is the segment of code which i am trying its arranges the prices well but the demand column is not adjusted accordingly. Any body can help me how i can do . Objective is arrange buyers based on prices indesending order than access their demands. Thanks
for i=1:17520
X(i,:)=buyer_price(i,:);
Y(i,:)=buyer_fl(i,:);
end
for i=1:17520
[sortedX(i,:), sortIndex(i,:)] = sort(X(i,:), 'descend');
sortedY=Y(sortIndexX);
end

Accepted Answer

Walter Roberson
Walter Roberson on 12 Nov 2020
%no loop solution
[sortedX, sortIndex] = sort(X, 2, 'descend');
sortedY = Y(sub2ind( size(Y), repmat((1:size(Y,1)).', 1, size(Y,2)), sortIndex));
This uses some advanced indexing techniques; do not expect to be able to understand it immediately.
The problem you were encountering is that you are sorting one row at a time, so the indices you are getting are indices just for that row -- but then you try to use them to access all of Y, without telling MATLAB which row number goes with each index.
The naive way of providing the indices would be to use Y(row_numbers, sortIndex) . That will not work: when you index an array using multiple vectors, then the results have all combinations of results. For example Y([2 5], [1 3 4]) would give back a 2 x 3 rectangular array, Y(2,1) Y(2,3), Y(2,4); Y(5,1), Y(5,3), Y(5,4) .
So you need a way to pair-up row numbers and column numbers one-by-one instead of getting the explosion like you would in this example. The way to do that in MATLAB is to translate each of the row/column pairs into linear indexes relative to the beginning of the array, and then index using the linear indexes. sub2ind() is the routine for doing that conversion of row/column pairs into linear indexes.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!