MATLAB Export Data
The objective of this tutorial is to demonstrate how to save MATLAB internal data to a file of defined formatting. The input saved variable is assumed to be to be similar to ones which obtained from using script and data file from MATLAB Import Data tutorial. This article will show how to use MATLAB command fprintf and some others to save data to the file.
Author(s): Dmitry I. Zhuk, Mark A. Tschopp
Assume that MATLAB have all the information and variables from MATLAB Import Data tutorial saved. Now the objective is to save this information using LAMMPS standard formatting for future use. This tutorial does not show now to calculate or obtain this data but only how to write existing information in a different format.
Here is one of the ways to save data to file.
fid1 = fopen(filename, 'w'); fprintf(fid1, '# Minimum Energy GB Structure for LAMMPS\n'); fprintf(fid1,'\n'); fprintf(fid1, '%d atoms\n', atoms); fprintf(fid1, '1 atom types\n'); fprintf(fid1, '%f %f xlo xhi\n', xlo, xhi); fprintf(fid1, '%f %f ylo zhi\n', ylo, yhi); fprintf(fid1, '%f %f ylo zhi\n', zlo, zhi); fprintf(fid1,'\n'); fprintf(fid1,'Atoms'); fprintf(fid1,'\n'); fprintf(fid1, '%d 1 %f %f %f\n', [double(atomID), Xpos, Ypos, Zpos]'); fclose(fid1);
Fopen command simply opens the file for editing with fileID "fid1". "w" here means to open file with permission to write. Fprintf command adds information to the opened file. Text to write goes in apostrophes. "\n" means to start with the next line. There are some other escape characters which are described in MATLAB help.
Variable can be also printed inside the text. Adding number format sign at the place where the actual number should go will do this. For example.
fprintf(fid, 'The wave traveled %d meters at the speed of %f meters per second', 100, speedofsound);
If the variable speedofsound is equal, for instance, to 340.29, then the result would be:
The wave traveled 100 meters at the speed of 340.29 meters per second
Note, that 100 here is not a variable but just a number.
Brackets in last fprintf function is needed to print only one of the variables on the line and then the other. Without them, the MATLAB would just print all the variables one after another, four on line. "double(atomID)" changes atomID type to double floating-point.