Читать книгу Applied Numerical Methods Using MATLAB - Won Y. Yang - Страница 16

1.1.2 Input/Output of Data Through Files

Оглавление

MATLAB can handle two types of data files. One is the binary format mat‐files named ***.mat. This kind of files can preserve the values of more than one variable, but will be handled only in the MATLAB environment and cannot be shared with other programming environments. The other is the ASCII dat‐files named ***.txt, which can be shared with other programming environments, but preserve the values of only one variable.

Beneath are a few sample statements for storing some data into a mat‐file in the current directory and reading the data back from the mat‐file.

>save ABC A B C %store the values of A,B,C into the file 'ABC.mat' >clear A C %clear the memory of MATLAB about A,C >A %what is the value of A? Undefined function or variable 'A' >load ABC A C %read the values of A,C from the file 'ABC.mat' >A % the value of A A= 1 2 3 4 5 6

If you want to store the data into an ASCII dat‐file (in the current directory), make the filename the same as the name of the data and type ‘ ‐ascii’ at the end of the save statement.

>save B.txt B -ascii

However, with the save/load commands into/from a dat‐file, the value of only one variable having the lowercase name can be saved/loaded, a scalar or a vector/matrix. Besides, nonnumeric data cannot be handled by using a dat‐file. If you save a string data into a dat‐file, its ASCII code will be saved. If a dat‐file is constructed to have a data matrix in other environments than MATLAB, every line (row) of the file must have the same number of columns. If you want to read the data from the dat‐file in MATLAB, just type the (lowercase) filename ***.txt after ‘ load’, which will also be recognized as the name of the data contained in the dat‐file.

>load b.txt %read the value of variable b from the ascii file 'b.txt'

At the MATLAB prompt, you can type ‘nm112’ (the filename excluding the extension name part “.m”) and <Enter> key to run the following M‐file “nm112.m” consisting of several file input(save)/output(load) statements. Then you will see the effects of the individual statements from the running results appearing on the screen.

%nm112.m clear A=[1 2 3;4 5 6] B=[3;-2;1]; C(2)=2; C(4)=4 disp('Press any key to see the input/output through Files') save ABC A B C %save A,B & C as a MAT-file named 'ABC.mat' clear('A','C') %remove the memory about A and C load ABC A C %read MAT-file to recollect the memory about A and C save B.txt B -ascii %save B as an ASCII-file file named 'b.txt' clear B load b.txt %read ASCII-file to recollect the memory about b b x=input('Enter x:') format short e x format rat, x format long, x format short, x

Applied Numerical Methods Using MATLAB

Подняться наверх