MATLAB Programming/Basic Reading and Writing data from a file

From Wikibooks, open books for an open world
< MATLAB Programming
Jump to: navigation, search


MATLAB Programming

Chapter 1: A Tutorial Introduction

Workspace
Variables

Chapter 2: Basic MATLAB Concepts

Saving and loading a MAT-file
MATLAB's Command Prompt
Basic Reading and Writing Data from a File

Chapter 3: Data Storage and Manipulation

Data Types and Operations on Point Values

Boolean and Rational
Strings
Portable Functions
Complex Numbers

Arrays and Matrices

What is an array?
Introduction to array operations
Vectors and basic vector operations
Struct Arrays
Cell Arrays
Sparse Matrices

Chapter 4: Graphics

Basic Graphics Commands
Annotating Plots

Chapter 5: M File Programming

Scripts
Comments
The Input Function
Control Flow
Loops and Branches
Error Messages
MATLAB Caveats
Debugging M Files

Chapter 6: Mathematical Manipulations

Linear Algebra

Simple matrix manipulation
More complicated matrix operations

Differential Equations

Ordinary Differential Equations
Partial Differential Equations

Chapter 7: More advanced I/O

Reading and writing from files
Writing and Reading to a Serial Port
Writing to a USB Port

Chapter 8: Examples

Filtering
Controls
Phase Vocoder and Encoder

Chapter 9: Object-Oriented Programming

Struct arrays
MATLAB Classes

Chapter 10: An alternative to MATLAB: Octave

What is Octave ?
Octave/MATLAB differences

Chapter 11: Toolboxes

Symbolic Math Toolbox
GUIDE
Simulink
Psych Toolbox

edit this box

Reading and Writing from a file: Command Line[edit]

Reading and Writing data from/to a .mat file[edit]

The quickest means 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 opend in MATLAB version 6+ the State-Space objects did not load.Spradlig (talk) 04:52, 31 March 2008 (UTC).

Saving Data[edit]

The save command is 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'))
  • 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')

Loading Data[edit]

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')

Reading and Writing from an Excel spreadsheet[edit]

Since analyzing data is one of the more common motivations for using input output I will start with reading and writing from a spreadsheet. I cover the command line first since it is often necessary to import the data while an m-function is being evaluated.

MATLAB makes it easy to read from an Excel spreadsheet. It has the built in command "xlsread". To use the xlsread function use the syntax:

>>g=xlsread('filename');

This line of code reads filename.xls (from the current directory) and places it in an identical array inside MATLAB called g. You can then manipulate the array g any way you want. Make sure that the file you choose is in the same directory were you save your M-files (usually the work directory) otherwise you get an error. You can specify the path to a file but, this can get messy.

To write data to an .xls the procedure is very similar. The xlswrite command below creates a spreadsheet called filename.xls in the current directory from the variable g:

>> xlswrite('filename',g);

NOTE: if you are using MATLAB 6.5 there is no "xlswrite" command (that I'm aware of). There are several ways to write to a file. The simplest way I have found is

fid=fopen('newFile.xls', 'w');
fprintf(fid,'%6.3f %6.3f %10.3f\n', g);           
fclose(fid);

You can substitute newFile.xls with .txt. Also, there might be some issues with formatting in Excel. The formatting issues can usually be handled inside Excel but if they can't you might have to play around with the fopen command parameters. This is pretty similar (if not the same) way you would write to a file in C.

Reading and Writing from and to other text files[edit]

If a file is not an excel spreadsheet, it can still be read using "load" function:

>> load newfile.txt

This works only if the text is entirely numerical, without special formatting. Otherwise you get an 'unrecognized character' error.

The easiest way to write to a non-excel file, or using MATLAB 6.5 or less, is to use the same code as that for writing excel files but change the extension. Usually there are no formatting difficulties with plain text files.

For reading more general text files, MATLAB does not have a function to do it easily (unless you have excel), but you can read very general text files (with different delimiters for both cells and text within cells) using the "textread.m" function in the MATLAB file exchange (do a google search to find it). You can also try to use fscanf if the formatting is consistent enough (i.e. consistent numbers of spaces, no mixing of strings and numbers in columns, and so on).

Reading and Writing from a data file: GUI[edit]

MATLAB contains a nice GUI application that will guide you through importing data from any recognized data file (usually .mat, .txt, or .xls on a Windows system). To use it, go to file > import data, and select the file you want. Then, choose what column separators are present (by selecting the appropriate radio button). Finally, click "next".

MATLAB saves the variable under a name similar to that of the file, but with modifications to make it conform with MATLAB syntax. Spaces are omitted, plusses and minuses are turned into other characters. To see the name MATLAB generated (and probably change it) type "who" in the command prompt.

External Resources[edit]

ControlTheoryPro.com

MatlabCodes.Webs.com