askvity

How to use load in MATLAB?

Published in MATLAB File I/O 3 mins read

Here is how to use the load function in MATLAB:

To use the load function in MATLAB, you provide the filename of the data you want to load. The primary purpose of load( filename ) is to load data from filename into the MATLABĀ® workspace. The way load behaves depends on the type of file you are loading.

Loading Different File Types with load

Based on the reference provided, the load function handles two main types of files:

  1. MAT-files (.mat): These are binary files specifically designed by MATLAB to store variables.
  2. ASCII files (.txt, .csv, etc.): These are plain text files containing numeric data.

Here's a breakdown of how load works for each type:

File Type Description in Reference Result in Workspace
MAT-file load(filename) loads variables from the file. Variables stored in the file appear directly in your workspace with their original names and values.
ASCII file load(filename) loads a double-precision array containing data from the file. A single variable appears in your workspace. By default, it's named after the filename (without the extension) and contains the data from the file as a double array.

Basic Usage Examples

Let's look at simple examples for each file type.

1. Loading a MAT-File

Assume you have saved some variables (e.g., myVar1, dataMatrix) into a file named mydata.mat using the save function.

  • Syntax:

    load( 'mydata.mat' );
  • Result:

    • After running this command, the variables myVar1 and dataMatrix will appear in your current MATLAB workspace, ready for use.
  • Practical Insight: This is the most common use of load for saving and restoring MATLAB sessions or specific variable sets.

2. Loading an ASCII File

Assume you have a simple text file named measurements.txt containing numerical data, like this:

1.2 3.4 5.6
7.8 9.0 1.1
2.3 4.5 6.7
  • Syntax:

    load( 'measurements.txt' );
  • Result:

    • A single variable named measurements (matching the filename) will be created in your workspace.
    • This variable will be a double-precision array containing the data from the file:
      measurements =
         1.2000   3.4000   5.6000
         7.8000   9.0000   1.1000
         2.3000   4.5000   6.7000
  • Practical Insight: This method is suitable for simple, uniformly formatted numeric data in text files. For more complex text file formats (like CSV with headers or mixed data types), functions like readmatrix, readtable, or textscan might be more appropriate.

In summary, the core functionality of load( filename ) is to populate your MATLAB workspace with data from the specified file, adapting its behavior based on whether the file is a MAT-file (loading variables) or a simple ASCII file (loading a double array).

Related Articles