Sorting a matrix based on another matrix

12 ビュー (過去 30 日間)
Keerthi Krishna
Keerthi Krishna 2022 年 11 月 28 日
コメント済み: Stephen23 2022 年 11 月 28 日
I have a csv file with the first two columns being names of individuals and their teams (both of which are strings) and the rest of the columns being a bunch of performance numbers (integers). I used readtable to import the data as it contained both strings and numbers. This is a 20x8 table called 'drivers'.
I then split the table into a 20x2 cell array called 'driver_names' for the names and teams, and a 20x6 double called 'driver_data' for the numbers.
I then did a few different operations on driver_data. What I need to do next is sort both driver_names and driver_data based in ascending order based on one column of driver_data but I'm not able to figure out how to do this.
Parts of the code are as such:
drivers = readtable("Drivers.csv","NumHeaderLines",1);
for j = (1:size(drivers,1))
driver_names(j,1:2) = drivers{j,1:2};
driver_data(j,:) = drivers{j,3:size(drivers,2)};
end
For now, I have sorted driver_data like this:
driver_data = sortrows(driver_data,2)
  1 件のコメント
Stephen23
Stephen23 2022 年 11 月 28 日
Simpler without the loop:
driver_names = drivers{:,1:2};
driver_data = drivers{:,3:end};

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2022 年 11 月 28 日
[driver_data,idx] = sortrows(driver_data,2);
driver_names = driver_names(idx,:);
  2 件のコメント
Keerthi Krishna
Keerthi Krishna 2022 年 11 月 28 日
Thank you, worked perfectly.
Just so I can learn, could you explain how exactly this works? I'm fairly new to MATLAB so it would be helpful
Stephen23
Stephen23 2022 年 11 月 28 日
The second output of SORTROWS is explained here:
Indexing is explained here (and other places):
The code sorts DRIVER_DATA exactly as you did, obtains the sort index, and uses that index to sort the rows of DRIVER_NAMES. Indexing is one of MATLAB's super powers, you need to learn how to use it.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by