# 4.1 Loading and Saving Data In MATLAB

The MATLAB load and save routines can be used to read and write both ASCII and binary data. These two commands are primarily used to read and write full-precision binary MATLAB format files. The structure of these MAT-files is discussed in detail in the MATLAB version 4 External Interface Guide. It is also possible to read and write ASCII files with these routines. The save command will create space or tab delimited files of either 8- or 16- digit ASCII form. Included here are some examples of the save command.

        save filename               % saves workspace to binary
                                    % file

        save filename X Y Z         % saves variables X Y Z to
                                    % binary file

        save filename X Y Z -ascii  % saves variables X Y Z to
                                    % ASCII file

        save filename X Y Z -ascii -tabs -double  % saves variables
                                    % X Y Z in tab delimited 16-
                                    % digit ASCII form

The load command will read any MAT-file created on any platform or any ASCII file with numeric space or tab delimited data.

       load file                   % loads file assuming file.mat
                                   % exists

       load file.txt               % loads file as ASCII

       load file.txt -ascii        % loads file as ASCII

       load file.dat -mat          % loads file as MAT-file

Users may find it necessary to use the -mat flag when loading MATLAB 3.5 MAT-files into version 4.

In MATLAB version 4, matrices with any non-zero entries and matrices with 10,000 or fewer elements are saved in double precision format, that is, 8 bytes per element. Files of this nature will load successfully into MATLAB 3.5. Matrices of more than 10,000 elements of all integer entries are saved in the following formats, requiring fewer bytes per element.

    Element Range          Bytes per Element
    0:255                  1
    0:65535                2
    -32767:32767           2
    -2^31+1:2^31-1         4
    other                  8

MAT-files of these forms will not load successfully into MATLAB 3.5. To convert these files into a format readable by version 3.5, load them into version 4 and add .1 to each element of the matrices. Resaving the data with the save command will create a double precision MAT-file that can be loaded into MATLAB 3.5. For example, the file in question contains the matrix, A, which consists of 10,500 integer elements. Load the file into MATLAB version 4 and enter the command

    A = A + .1;

Save the new data with

    save file A

Load the file into MATLAB 3.5 with the load command.

(c) Copyright 1994 by The MathWorks, Inc.