Homework Question: File I/O reading and loops

% 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

Answers (1)

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)

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Tags

Asked:

on 7 Dec 2015

Answered:

on 7 Dec 2015

Community Treasure Hunt

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

Start Hunting!