Effacer les filtres
Effacer les filtres

why am I getting error?

2 vues (au cours des 30 derniers jours)
Manav Divekar
Manav Divekar le 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);

Réponse acceptée

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

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by