对struct array进行排序

1. 对结构体数组(struct array)进行排序:

即对s_info进行排序

n=3;
%% 初始化一个cell数组
c_info=cell(n,1);
id=[12 3 8];

name={'x','l','h'};
age=[20 22 24];
for i=1:n;
    c_info{i}.id=id(i);
    c_info{i}.name=name{i};
    c_info{i}.age=age(i);
end

%% 初始化一个struct数组
s_info=repmat(struct('id',[],'name',[],'age',[]),3,1);

for i=1:n
    s_info(i).id=id(i);
    s_info(i).name=name{i};
    s_info(i).age=age(i);
end

%% sort for an struct array 
[sx,sx]=sort([s_info.id],'ascend');
ss=s_info(sx);

2. 对嵌入在cell中的结构体进行排序

即对c_info进行排序。
将cell数组转换为struct数组

%% 如果对nested in cell的结构体进行排序呢?即如果对c_info进行排序呢?
cs_info=[c_info{:}];
[sx2,sx2]=sort([s_info.id],'ascend');%ascend升序,descend降序
ss2=c_info(sx2);

上面使用[sx,sx]的原因是:

% an example
     r=randperm(5);
% ... let's look at what happens under the hood
     format debug; % must reset afterwards!
% typical use
     [dum,sx]=sort(r)
% frugal use
     [sx,sx]=sort(r)

当然也可以将第一个输出变量设置为空:

A couple tips. Not sure if these worked back when the original post was made, but for MATLAB 2015b:
%几个建议
#1. Use a null for the first argument, rather than writing sx twice:
%%将第一个参数指定为空,而不是写两次sx
[~,sx] = sort([s.f]);

#2. If the field, f, is a string, then enclose in curly brackets:
%%如果安装属性域为string类型进行排序,那么使用花括号括起来
[~,sx] = sort({s.f});

#3. If the field, f, is a date stored as a string, then convert to datetime prior to sorty
%% 如果f是通过string形式存储的日期,那么先转换为日期然后在排序
[~,sx] = sort(datetime({s.f}));

3对结构体数组中的一个矢量的某个值进行排序

即:按照s_info.fea(4)进行排序,即第四个特征进行排序。
这里写图片描述
将第4个特征取出来作为结构体的一个属性进行排序。
代码:


clc;clearvars;close all;
id=[12 3 8];
name={'x','l','h'};
age=[20 22 24];
fea={[3 5 9 10],[1 0 4 7],[11 23 9 2]};
n=3;
%% 初始化一个struct数组
s_info=repmat(struct('id',[],'name',[],'age',[],'fea',[]),3,1);%fea feature

for i=1:n
    s_info(i).id=id(i);
    s_info(i).name=name{i};
    s_info(i).age=age(i);
    s_info(i).fea=fea{i};
end
%%对fea的第4个特征进行排序
for i=1:n
    s_info(i).f=s_info(i).fea(4);
end
% 按照升序进行排序
[~,ind]=sort([s_info.f],'ascend');
res=s_info(ind);

1.参考文献:
https://cn.mathworks.com/matlabcentral/newsreader/view_thread/106355

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值