Reading and Writing MATLAB Data

From ControlTheoryPro.com

Jump to: navigation, search
Symbol.gif
Reading and Writing MATLAB Data
Green carrot left.gif
All MATLAB Articles Read and Write Excel files in MATLAB
Green carrot.jpg
In order to prevent spam, users must register before they can edit or create articles.

1 Reading and Writing data from/to a .mat file

The quickest mean of saving and retrieving data is through the binary .mat file format MATLAB provides. This is the native format for MATLAB.

  • Note: This author has had some problems with certain classes not being saved correctly when saving data using version 7 for use in version 6. Most data items will work just fine. Of particular interest was an issue with State-Space objects that were saved using version 7 to a version 6 compatible file. When the file was opened in MATLAB version 6+ the State-Space objects did not load.Gabe 23:42, 30 March 2008 (CDT)

1.1 Saving Data

The save command is the used to save workspace data to a file.

  • Save all workspace data to the file mySave.mat in the current directory.
 >> save('mySave.mat')
 >> save(fullfile(pwd, 'mySave.mat'))					%	Explicit command equivalent to the line above
  • Save just the variables myData1 and myData2 to mySave.mat.
 >> save('mySave.mat', 'myData1', 'myData2')
  • Save all myData variables to mySave.mat.
 >> save('mySave.mat', 'myData*')
  • Save all myData variables to a mySave.mat file compatible with version 6 of MATLAB.
 >> save('mySave.mat', 'myData*', '-v6')
  • Save all myData variables to an ASCII file.
 >> save('mySave.txt', 'myData*', '-ASCII')
  • Append new variables to the data file.
 >> save('mySave.mat', 'newData*', '-append')

1.2 Loading Data

The load command is used to load data from a file into the current workspace.

  • Load all variables from the file mySave.mat into the current workspace.
 >> load('mySave.mat')
 >> load(fullfile(pwd, 'mySave.mat'))
  • Load just the variables myData1 and myData2.
 >> load('mySave.mat', 'myData1', 'myData2')
  • Load all myData variables.
 >> load('mySave.mat', 'myData*')
  • Get a cell array of variables in saved file.
 >> whos('-file', 'mySave.mat')