Resort struct elements by one field values

6 ビュー (過去 30 日間)
REN
REN 2011 年 3 月 6 日
Hello,
In a struct
A = struct('f1', [some values], 'f2', [some values])
Can we resort elements of A by increasing order in f1?
For example:
A = struct('f1', [some values], 'f2', [some values])
A.f1 is a 1 X 5 double value [3, 4, 1, 2, 5]
A.f2 is 1 X 5 double value [val 3, val 4, val 1, val 2, val 5]
How to create another struct B as
B = struct('f1', [1 , 2, 3, 4, 5], 'f2', [val 1, val 2, val 3, val 4, val 5])?
  1 件のコメント
Walter Roberson
Walter Roberson 2011 年 3 月 6 日
One can re-sort in Matlab, and one can resort -to- Matlab, but I didn't know of any Matlab Resort ;-)

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

採用された回答

Matt Tearle
Matt Tearle 2011 年 3 月 6 日
Would this do it?
a.foo = [3, 4, 1, 2, 5];
a.bar = {'a','b','c','d','e'};
% assuming b already exists
b = a;
% reorder b
[sortfoo,idx] = sort(a.foo);
b.foo = sortfoo;
b.bar = b.bar(idx)
  1 件のコメント
REN
REN 2011 年 3 月 6 日
yes, thanks all

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

その他の回答 (1 件)

Giovanni Soldi
Giovanni Soldi 2011 年 3 月 6 日
Try in this way:
B = struct('f1',sort(A.f1),'f2',sort(A.f2));
  2 件のコメント
REN
REN 2011 年 3 月 6 日
but in f2 val 3, val 4, val 1, val 2, val 5 can not be sorted
f2 can be only sorted according to value in f1
REN
REN 2011 年 3 月 6 日
even f2 can be sorted by increasing oder,
if try
B = struct('f1',sort(A.f1),'f2',sort(A.f2));
a result maybe
B.f1 = [1 2 3 4 5]
B.f2 = [val 2 val 3 val 4 val 5 val 1]
because val 2 < val 3 < val 4 < val 5 < val 1

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by