Read data from file and print information for whom has the required criteria?

There is a data file with the last name, first name, blood type, - or + Rh factor, and ID number. donors.dat - The data looks like this, for example:
Donald Bird A + 120.1
George Aaron AB - 111.1
Claire Stuart O - 108.1
Jan Doe B + 102.3
Doug Smith AB + 110.5
I need a script that will read the data file and print out all the information for donors whom have the blood type AB.
So the outcome of the script, from the above data should be:
George Aaron AB - 111.1
Doug Smith AB + 110.5
This is what I have so far. What is the problem with my script?
data = 'donors.dat';
FID = fopen(data, 'r');
cn = 0;
if strcmp(data(:,3),'AB') == 1;
cn = cn + 1;
cs{cn}=donors;
disp(donors)
break
end

 Respuesta aceptada

Dear Nora, here is the code which reads the file and then shows information for people having blood group 'AB':
ID = fopen('filename.txt');
a = textscan(ID, '%s%s%s%s%f');
fclose(ID)
firstname = a{1};
lastname = a{2};
bloodtype = a{3};
Rhfactor = a{4};
IDnumber = a{5};
info{1, 1} = 'First name';
info{1, 2} = 'Last name';
info{1, 3} = 'Blood type';
info{1, 4} = 'Rh factor';
info{1, 5} = 'ID number';
count = 2;
for i = 1:length(bloodtype)
if bloodtype{i} == 'AB'
info(count, 1) = firstname(i);
info(count, 2) = lastname(i);
info(count, 3) = bloodtype(i);
info(count, 4) = Rhfactor(i);
info{count, 5} = IDnumber(i);
count = count + 1;
end
end
disp('People with blood group AB are:')
disp(info)
I hope it helps. Good luck!

4 comentarios

Thank you! Is there a more simple way to display their information then having to assign each part of the data to a certain information like done for info above? For example, is there a way to display that row in the data when the for statement is satisfied?
Then you can reduce the code in the following way:
ID = fopen('filename.txt');
a = textscan(ID, '%s%s%s%s%f');
fclose(ID);
firstname = a{1};
lastname = a{2};
bloodtype = a{3};
Rhfactor = a{4};
IDnumber = a{5};
for i = 1:length(bloodtype)
if bloodtype{i} == 'AB'
fprintf('%s\t%s\t%s\t%s\t%f\n', firstname{i}, lastname{i}, bloodtype{i}, Rhfactor{i}, IDnumber(i))
end
end
I hope it works fine. Good luck!
It does. Thanks again!
You are welcome

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Fortran with MATLAB en Centro de ayuda y File Exchange.

Preguntada:

el 27 de Oct. de 2013

Comentada:

el 27 de Oct. de 2013

Community Treasure Hunt

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

Start Hunting!

Translated by