cell配列に格納さ​れたインスタンスをプ​ロパティ値で並べ替え​る方法

조회 수: 1 (최근 30일)
光俊 河津
光俊 河津 2022년 6월 16일
댓글: 光俊 河津 2022년 6월 17일
下のように、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の順に並べ替えたい

채택된 답변

Atsushi Ueno
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の順に並べ替えたい
objects = 1×4 cell array
{1×1 MyClass} {1×1 MyClass} {1×1 MyClass} {1×1 MyClass}
% score1だけを取り出す
score1 = cellfun(@(x) x.score1, objects)
score1 = 1×4
10 3 5 11
% score1を降順にソート(並び順のみ取得)
[~, ind] = sort(score1, 'descend')
ind = 1×4
4 1 3 2
% objectsを上記並び順に並べ替える
objects2 = objects(ind)
objects2 = 1×4 cell array
{1×1 MyClass} {1×1 MyClass} {1×1 MyClass} {1×1 MyClass}
% score1の大きい順にソートされた事を確認
objects2{:}
ans =
MyClass with properties: score1: 11 score2: 2
ans =
MyClass with properties: score1: 10 score2: 5
ans =
MyClass with properties: score1: 5 score2: 1
ans =
MyClass with properties: score1: 3 score2: 12
  댓글 수: 1
光俊 河津
光俊 河津 2022년 6월 17일
ありがとうございます。
無事やりたいことができました。

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!