Filter löschen
Filter löschen

why am I getting error?

2 Ansichten (letzte 30 Tage)
Manav Divekar
Manav Divekar am 18 Nov. 2021
Beantwortet: Image Analyst am 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);

Akzeptierte Antwort

Image Analyst
Image Analyst am 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

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by