您的位置:首页 > 其它

找到结构体数组某个属性满足条件的其他属性\或满足属性条件的样本

2016-10-19 10:47 204 查看

找到结构体数组某个属性满足条件的其他属性

描述:每一个样本是通过一个结构体的形式进行描述。多个样本通过一个结构体数组进行描述。其中每一个样本都有一个唯一的标识属性index。我们的目的是找到:某个属性满足条件的,所有样本的标示index。

例如,在下面的实验中,我们找到年龄大于21的所有人的index,或者所示唯一的id。



clc;clearvars;close all;
n=3;
id=[12 3 8];
name={'x','l','h'};
age=[20 22 24];
index=[2 1 3];
%% 初始化一个struct数组
s_info=repmat(struct('index',[],'id',[],'name',[],'age',[]),3,1);

for i=1:n
% index表示样本的id,每一个样本有唯一的一个Id
s_info(i).index=index(i);
s_info(i).id=id(i);
s_info(i).name=name{i};
s_info(i).age=age(i);
end

%% 找到年龄大于21的所有样本索引
%% 注意,这里的两个中括号都是必须的,其利用了两种属性,一个类似于结构体排序的,然后要加上中括号,另外一个是将结构体转换为数组的,然后要加上中括号
s_ind=[s_info([s_info.age]>21).index];

disp('over...');


结果:

s_ind=[1 3]

满足属性条件的样本

% the behavior of struct likes data table in database
student_table = repmat(struct('id',[],'name',[],'sex',[],'math_score',[]),5,1);

student_table(1) = struct('id','2012011601','name','zhangsan','sex','男','math_score',96);
student_table(2) = struct('id','2012011602','name','lisi','sex','女','math_score',90);
student_table(3) = struct('id','2012011603','name','wanger','sex','男','math_score',86);
student_table(4) = struct('id','2012011604','name','mazi','sex','男','math_score',70);
student_table(5) = struct('id','2012011605','name','kongsheng','sex','男','math_score',92);

% select * where sex='nan'&&math_score>90
excel_students = student_table(([student_table.sex]=='男')&([student_table.math_score]>=90));

for i = 1:length(excel_students)
disp(excel_students(i));
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐