フィルターのクリア

why am I getting error?

2 ビュー (過去 30 日間)
Manav Divekar
Manav Divekar 2021 年 11 月 18 日
回答済み: Image Analyst 2021 年 11 月 18 日
i am trying to write a code without cell2struct function to get female names between age 30 and 40 from following input
>> disp(filterpatients_struct( struct( ...
'name', {'mary','john','anna','paul','elaina'}, ...
'gender',{'f', 'm', 'f', 'm', 'f'}, ...
'age' ,{25, 35, 30, 22, 38} ) ));
The code i did so far
function [patient] = filterpatients_struct(data)
S = struct;
S.name = strcmp(data(1,:),'name');
S.gender = data(strcmp(data(2,:),'gender'),1);
S.age = data(strcmp(data(3,:),'age'),1);
% Index of females
idx = strcmp(S.gender,'f') ;
% age criteria
value = S.age(S.age(idx) >=30 & S.age(idx) <= 40 );
patient = value;
error i am getting
Index in position 1 exceeds array bounds (must not exceed 1).
Error in filterpatients_struct (line 4)
S.gender = data(strcmp(data(2,:),'gender'),1);

採用された回答

Image Analyst
Image Analyst 2021 年 11 月 18 日
Try it this way:
% Demo by Image Analyst.
clc; % Clear the command window.
fprintf('Beginning to run %s.m ...\n', mfilename);
s = struct( ...
'name', {'mary','john','anna','paul','elaina'}, ...
'gender',{'f', 'm', 'f', 'm', 'f'}, ...
'age' ,{25, 35, 30, 22, 38} );
filterpatients_struct(s)
fprintf('Done running %s.m\n', mfilename);
function patientNames = filterpatients_struct(data)
allNames = {data.name}
allGenders = {data.gender}
allAges = [data.age]
% Get indexes of females:
femaleIndexes = contains(allGenders, 'f')
% Get indexes where age is between 30 and 40 inclusive:
ageIndexes = (allAges >= 30) & (allAges <= 40)
% Get names where both criteria are true:
bothTrue = ageIndexes & femaleIndexes
patientNames = allNames(bothTrue)
end

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by