Reading Data with Matlab
Matlab is a language for manipulating data right away. Normally, you explore the data until you get something acceptable and then you may want to start putting your code into m-files (MatlabFunction). At this point, it can sometimes be interesting to preset variables via a configuration files. For reading (as well as for writing) Matlab provides a similar functionality as C: e.g. FOPEN, FSCANF, FPRINTF and FCLOSE.
- First, download the sample configure file
attachment:conf.txt and save it to your current working directory. Then try the following
> fid = fopen('conf.txt')
ans =
3
- The file conf.txt was opened and you can now access it via the file identifier (FID) "3". The file identifier increases with every file you open (at least under Linux) and you should always store it in variable rather then using the number directly. To read the content of the file use fscanf. As the first argument it takes the file identifier given by FOPEN. The second argument specifies what kind of data type you want to read (e.g. "s" for strings or "i" for integers). The last parameters is optional, if you obmit it, FSCANF will read the complete file and return all entries in vector. Here we just want to read one value
> hello = fscanf(fid, '%s', 1)
- To read an integer type
> answer = fscanf(fid, '%i', 1)
In the end, do not forget to close the file with FCLOSE.
> fclose(fid);
Writing Data
- Write data files is quite similar to reading. The only difference is that you must explicitly open the file for writing with an extra 'w' parameter, and substitute FSCANF with FPRINTF. Simply try to write the variables HELLO and ANSWER with the following commands
> fid = fopen('test.txt', 'w');
> fprintf(fid, '%s', hello);
- You can print a tabulator with '\t'
> fprintf(fid, '\t');
> fprintf(fid, '%i', answer);
> fclose(fid);
- To see whether it works use the TYPE command
> type test.txt
PS: You can combine multiple FPRINTF command into one by concatenating the format string (here: '%s', '\t' and '%i').
...
> fprintf(fid, '%s\t%i', hello, answer);
...
Ok, that's it.