필터 지우기
필터 지우기

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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by