MATLAB How can I properly save and manipulate data in MATLAB using text files?

  • Thread starter Thread starter Saladsamurai
  • Start date Start date
  • Tags Tags
    Data File Matlab
AI Thread Summary
To properly save and manipulate data in MATLAB using text files, it's essential to use the correct commands for loading and saving data. The 'load' command can create issues when dealing with text files, as it defaults to binary format; using 'dlmread' is recommended for better control over delimiters and headers. The 'fprintf' function is used to format the output when saving data, allowing for precise control over how the matrix is written to the file. For saving matrices as text files, using the '-ascii' option with the 'save' command can also be beneficial. Understanding these commands will help achieve the desired output format for the new text file.
Saladsamurai
Messages
3,009
Reaction score
7
How do I make this happen?



Code:
E=load('elements.txt');
EE=2*E;
save('poop.txt','EE')

It loads elements.txt
doubles the matrix
stores the results in a new text file

this does not work. It creates a new txt file but there is not much in it besides
the "created on 'this date & time' info"

I am having trouble deciphering which command I should be using
for this.

Any ideas?
Thanks,
Casey
 
Physics news on Phys.org
Okay, I got it using this:
Code:
E=load('elements.txt');
EE=3*E;
fid=fopen('poop.txt','w');
fprintf(fid,'   %8.2f    %8.2f   %8.2f   %8.2f     %8.2f\n ',EE)
fclose(fid);

However, this line is what is getting me. I don't know what it means or understand the syntax:
Code:
fprintf(fid,'   %8.2f    %8.2f   %8.2f   %8.2f     %8.2f\n ',EE)

the imported file is a 20 x 5 matrix

then it is multiplied by a scalar and exported to a new file.

I would like the new file to look like a new 20 x 5 matrix.

How do I do that?

Thanks,
Casey
 
fprintf is just the standard C style output function (in this case, it's outputting to the file specified by fid instead of to the screen):
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fprintf.html

The problem with your approach is that, by default, the 'load' and 'save' commands load and save binary files that encode some matrix. If you use the -ascii option, it'd save more along the lines of what you're trying to do (though you can always use the C-style fprintf and fscanf):
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/load.html
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/save.html
 
It is usually better to use "dlmread" instead of "load" when handling text files, the former let's you define which delimiter is used (e.g. space or tab) and you can also skip the the first few columns or lines. This is very useful if the file has a header (e.g. the names of the columns).
 
Back
Top