tags:

views:

124

answers:

2

I am using the following functions for writing and reading 4098 floating point numbers in MATLAB:

Writing:

fid = fopen(completepath, 'w');

fprintf(fid, '%1.30f\r\n', y) 

Reading:

data = textread(completepath, '%f', 4098);

where y contains 4098 numbers. I now want to write and read 3 strings at the end of this data. How do I read two different datatypes? Please help me. Thanks in advance.

+1  A: 

Well, you can write out a string at any point when you are writing to the file with the following:

fprintf(fid, '%s', mystring);

Of course, you might want something more like the form you gave:

fprintf(fid,'%s\r\n', mystring);

And you could mix the floating point with the string like so:

fprintf(fid, '%1.30f %s\r\n', y, mystring);

If you are dealing with mixed data types, you might want to use fscanf instead of textread if the formatting isn't very regular. For instance,

data = fscanf(fid, '%s', 1);

reads one character string from the file.

Take a look at the help files for fscanf for more information on how to use it. These functions are pretty much ANSI C functions (fprintf and fscanf I mean) so you find more info on the web about them quite easily.

Justin Peel
+1  A: 

Here's an example of what I think you want to do, using TEXTSCAN for reading the file instead of TEXTREAD (which will be removed in a future version of MATLAB):

%# Writing to the file:

fid = fopen(completepath,'w');  %# Open the file
fprintf(fid,'%1.30f\r\n',y);    %# Write the data
fprintf(fid,'Hello\r\n');       %# Write string 1
fprintf(fid,'there\r\n');       %# Write string 2
fprintf(fid,'world!\r\n');      %# Write string 3
fclose(fid);                    %# Close the file

%# Reading from the file:

fid = fopen(completepath,'r');      %# Open the file
data = textscan(fid,'%f',4098);     %# Read the data
stringData = textscan(fid,'%s',3);  %# Read the strings
fclose(fid);                        %# Close the file
gnovice

related questions