% Sample Data
I need to Open and read the data file and understand its format. Write a function that takes one input argument: the blood type in the format of a string.The function will display the names of all donors with the same blood type as the input argument.
% This is what I have so far
function FindDonors (Bloodtype)
%read in the data
[fid,msg] = fopen('donors.dat','r');
if fid == -1
errorlg(msg);
else
aline = fgetl(fid);
%
% I think I will need a while loop and compare the input argument to my data but how did I loop through my data file to the blood type and add it to a vector to be displayed
%
ret = fclose(fid);
if ret ~= 0
errordlg('File cannot be closed.');
end

답변 (1개)

Chad Greene
Chad Greene 2015년 12월 7일

0 개 추천

You don't need a while loop. You typically want to avoid loops because they're computationally slow and loops can be somewhat of a pain to debug.
I'd start by reading the data with textscan. The syntax for textscan is not intuitive and may take a little tinkering, but it's the data import function that can handle almost anything you throw at it. I'm not sure exactly what your data file looks like, but you may be able to read it like this:
fid = fopen('donors.dat');
D = textscan(fid,'%s %s %f %f %s %s','headerlines',1);
fclose(fid);
Then last names and blood types will be columns 2 and 5, respectively:
surname = D{2};
bloodtype = D{5};
Use logical indexing to avoid loops. The strcmpi function will tell you the indices of all donors with type AB blood:
ind = strcmpi(bloodtype,'AB');
Want to know the last names of all donors with AB blood?
surname(ind)

카테고리

도움말 센터File Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

태그

질문:

2015년 12월 7일

답변:

2015년 12월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by