Page 837 - Mechatronics with Experiments
P. 837
®
®
MATLAB , SIMULINK , STATEFLOW, AND AUTO-CODE GENERATION 823
®
3. From an M-file where data is defined following the MATLAB syntax (this is the most
®
common form of inputing data in MATLAB environment), using the ”filename” in
the program or in command window.
®
4. From any file in a format supported by MATLAB such as “filename.txt” or “file-
name.dat,” including Excel spreadsheet data file, “filename.xls.”
>> n = input (’Enter value for n : ’) ; % Inputs numeric data
to variable ’n’.
To enter a vector or matrix, use the same notation that we use in m-script file or
Command Window, i.e.
>> v = input (’Enter value for v: ’) ; % Inputs numeric data
for vector v
[1 2 3];
>> matrix1 = input (’Enter value for Matrix1: ’) ; % Inputs
% numeric data for vector v
[ 1 2 3 ;
4 5 6 ;
7 8 9 ] ;
The entered data are assigned to the variable on the left side of the assignment
statement.
Formatted input and output can be accomplished using fscanf() and fprintf() func-
tions, respectively, which are similar to the same named functions in C language. Before a
file can be accessed for read/write operations, it must be opened with the fopen() function.
When the read/write operations are completed for the current application, the file should
be closed using the fclose() function. As a result, there are typically four functions used for
formatted file I/O operations,
>> name = input (’Enter string data for name ’, ’s’) ;
% enters the string data (specified by ’s’) into
variable ’name’
>> filename ;
% executes the filename.m
% all the data defined in the m-file becomes part
% of the MATLAB® workspace and
% therefore accessible to the program.
>> load filename
% loads the variables saved in the filename.mat file
% which was saved before.
>> load(’filename.dat’, v)
% Loads ASCII data from the file to variable v
>> save
% saves all workspace variables to matlab.mat file in
binary format.
>> save filename
% save all of the workspace variables in the filename.mat
in binary format.