Hundurinn Nero
Hundurinn Nero

Reputation: 83

Read data from text file and passing to function

I got a this program which takes in all it data from a .txt file. It is possible to read the required data from the text file and pass that data to a function to work with? I have tried reading the data first and passing it to the function but then my plot refuses to work.
Right now I am doing it by sending in the name of the text file to the function and then read the data but this means that I am reading the data each time I call the function and I was hoping that I could just read the data once and then pass it on to the function. I think that not reading the data many times would speed up my program considerable.

My code looks like this

main.m

 young bein_AB_light.txt %%calling the function with bein_AB_light.txt as parameter.

young.m

function young(filename)

fid = fopen(filename,'r');
C = textscan(fid,'%*f%*f%*f%*f%f');
fclose(fid);

Y=10500*C{1}.^2.29; %

plot(C{1},Y,'.K')

if(strfind(filename,'AB'))
   xlabel('BMD[g/cm^3]');
   ylabel('Youngstudull');
   title('Reiknadur Youngstudull fyrir AB bein')
else
   xlabel('BMD[g/cm^3]');
   ylabel('Youngstudull');
   title('Reiknadur Youngstudull fyrir SCI bein')
end
end

EDIT... This is what I was trying but it gives me error when it tries to plot. Plot does not accept filename{1} to use as the X coordinites. I have also tried to use cell2mat function to change the input but that did not work.

main.m

fid = fopen(filename,'r');
AB_Bein = textscan(fid,'%*f%*f%*f%*f%f');
fclose(fid);
young AB_bein %%calling the function with AB_Bein as parameter.

young.m

function young(filename)



Y=10500*filename{1}.^2.29; %

plot(filename{1},Y,'.K')

if(strfind(filename,'AB'))
   xlabel('BMD[g/cm^3]');
   ylabel('Youngstudull');
   title('Reiknadur Youngstudull fyrir AB bein')
else
   xlabel('BMD[g/cm^3]');
   ylabel('Youngstudull');
   title('Reiknadur Youngstudull fyrir SCI bein')
end
end

Upvotes: 0

Views: 369

Answers (1)

Trogdor
Trogdor

Reputation: 1346

it's possible that your problem is the way you are calling young.

If I create a function

function fileContents= young(filename)

fid = fopen(filename,'r');
C = textscan(fid,'%*f%*f%*f%*f%f');
fclose(fid);
fileContents=C{1};

and then call it using

fileContents= young('textfile.txt');

rather than

young textfile.txt

That brings the data from the file out into the variable named fileContents

Upvotes: 1

Related Questions