对struct array进行排序

来源:互联网 发布:java缺少返回语句 编辑:程序博客网 时间:2024/06/06 11:07

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 featurefor 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

0 0