How to sort a structure by numbers in one of its fields?

3 ビュー (過去 30 日間)
Scott Rauscher
Scott Rauscher 2012 年 10 月 31 日
First of all, I have used a workaround to label my structure fields as distances as the following:
RX.(['d',num2str(distance{1})])(:,1) = data(:,45); % COTS 1, X-axis
RX.(['d',num2str(distance{1})])(:,2) = data(:,46); % COTS 1, Y-axis
etc.
so that my structure in the end looks like this:
d0: [600000x6 double]
d100: [525000x6 double]
d10: [550000x6 double]
d20: [475000x6 double]
d2: [550000x6 double]
d30: [450000x6 double]
d40: [525000x6 double]
d4: [600000x6 double]
d50: [525000x6 double]
etc.
I would like to be able to sort the fields in the structure so that they'd end up as
d0: [600000x6 double]
d2: [550000x6 double]
d4: [600000x6 double]
d6: [600000x6 double]
d8: [600000x6 double]
d10: [600000x6 double]
d20: [600000x6 double]
etc.
I can get as far as
RXnames = fieldnames(RX);
for j = 1:length(RXnames)
RXd(j) = regexpi(RXnames{j},'d(\d\d*)','tokens');
RXd(j) = RXd{j};
end
RXd = RXd';
which gives me the distances in a string array:
'0'
'100'
'10'
'20'
'2'
'30'
'40'
'4'
'50'
'60'
'6'
'70'
'80'
'8'
'90'
and then I can str2double them to a number array which I can then sort, but then I lose association with the fields. Does anyone know of a way to sort the way I'm describing?
Thanks to anyone in advance!
Scott

採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 10 月 31 日
eg
a = struct('d100',randi(125,4,5),'d458',3,'d7',rand(3),'d0','sd456'); % your data
p1 = regexp(fieldnames(a),'\d*','match');
[i1,i1] = sort(str2double(cat(1,p1{:})));
out = orderfields(a,i1)
  1 件のコメント
Scott Rauscher
Scott Rauscher 2012 年 11 月 1 日
Ah, perfect. There's some smart people on here...
Thank you

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

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 31 日
編集済み: Azzi Abdelmalek 2012 年 10 月 31 日
s=fieldnames(x)
c=char(s)
s1=cellfun(@(x) (regexp(x,'\d+','match')),s,'un',0)
s2=cellfun(@str2double,s1)
[s3,idx]=sort(s2)
for k=1:numel(s2)
b.(['d' num2str(s3(k))])=x.(strtrim(c(idx(k),:)))
end
x=b
  1 件のコメント
Scott Rauscher
Scott Rauscher 2012 年 11 月 1 日
編集済み: Scott Rauscher 2012 年 11 月 1 日
This worked perfectly, but the one right above you took less lines of code. Thank you though!!

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


Milos
Milos 2012 年 10 月 31 日
You will have to pad field names with zeros:
d000
d005
d010
d077
d100
and then you can sort the fields using function:
orderfields

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by