cell配列に格納されたインスタンスをプロパティ値で並べ替える方法
1 回表示 (過去 30 日間)
古いコメントを表示
下のように、score1とscore2というプロパティを持つクラスを定義し、
そのクラスのインスタンス(obj1~obj4)をcell配列(下コードのobjects)に格納したとき、
score1の大きい順にソートしたい。
classdef MyClass
properties
score1 int8
score2 int8
end
methods
function obj = MyClass(score1, score2)
obj.score1 = score1;
obj.score2 = score2;
end
end
end
% クラスのインスタンスを生成
obj1 = MyClass(10, 5);
obj2 = MyClass(3, 12);
obj3 = MyClass(5, 1);
obj4 = MyClass(11, 2);
% インスタンスのcell配列に格納
objects = {obj1, obj2, obj3, obj4} % ←この配列をscore1の順に並べ替えたい
0 件のコメント
採用された回答
Atsushi Ueno
2022 年 6 月 16 日
% クラスのインスタンスを生成
obj1 = MyClass(10, 5);
obj2 = MyClass(3, 12);
obj3 = MyClass(5, 1);
obj4 = MyClass(11, 2);
% インスタンスのcell配列に格納
objects = {obj1, obj2, obj3, obj4} % ←この配列をscore1の順に並べ替えたい
% score1だけを取り出す
score1 = cellfun(@(x) x.score1, objects)
% score1を降順にソート(並び順のみ取得)
[~, ind] = sort(score1, 'descend')
% objectsを上記並び順に並べ替える
objects2 = objects(ind)
% score1の大きい順にソートされた事を確認
objects2{:}
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!