why am I getting error?

1 view (last 30 days)
Manav Divekar
Manav Divekar on 18 Nov 2021
Answered: Image Analyst on 18 Nov 2021
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);

Accepted Answer

Image Analyst
Image Analyst on 18 Nov 2021
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

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!