Title: MATLAB Input-Output Statements
1MATLAB Input-Output Statements
Nafees Ahmed Asstt. Professor, EE Deptt DIT,
DehraDun
2Introduction
- Data Input
- Three methods
- 1. Assign data to variables through an
assignment statement - 2. Input data from Keyboard
- 3. Read data from a file stored in computer memory
3Data Input
- 1. Assign data to variables through an
assignment statement - gtgtx2
- gtgty34.2
- gtgtnameRaheel Sufyaan
- or
- gtgtx2 y34.2 nameRaheel Sufyaan
4Data Input
- 2. Input data from Keyboard (Interactive input)
- Input Function
- Keyboard Command
- menu function
- pause command
5Data Input
- I. Input Function See different version of this
function - gtgtrinput(Enter radius in meters)
- Enter radius in meters56 r will become integer
- r
- 56
- Enter radius in meters ninety six r will
become string , Note compulsory - r
- ninety six
- gtgtrinput(what is your fathers name, s) r
string, - what is your fathers name Nafees Ahmed Note
not required - r
- Nafees Ahmed
6Data Input
- II. Keyboard return command
- keyboard command when included in a script
file returns control to the keyboard at the point
where command occurs. The command window prompt
is prefixed by the letter k. This command is
used for - Check the intermediate results in the program
- Make changes in variables value if required
- Add new MATLAB commands in the program
- Exp Make a .m file for the following code and
run it - A10
- B16
- XAB
- YX/2
- Keyboard check the value of Y and change Y10,
after finishing write return command, it
will execute rest program - ZA-B
7Data Input
- III. menu function
- for pictorial selection. Syntax is
- Imenu(title, option1, option2,..)
- Exp Make a .m file for the following code and
run it - imenu('Select your favorite name','Teenu','Sumbul
','Humera') - if i1
- disp('Teenu is your wife')
- elseif i2
- disp('Sumbul is yr sis-in-low')
- elseif i3
- disp('Humera is yr sis-in-low')
- else
- disp('Bewakoof kuch to select karo')
- end
-
8Data Input
- IV. pause command
- pause command temporarily halts the current
computation and waits for the user to give a
command to resume the computations. Pressing any
key resumes the computation. - pause(k) command stops the computation for k
seconds. - Exp Make a .m file for the following code and
run it - P1 2 3 4 Q5 5 7 8
- disp('The matrix P is given as')
- disp(P)
- disp('Program is paused, please press any key to
display matrix Q') - pause
- disp('The matrix Q is given as')
- disp(Q)
- ZPQ
- disp('Program is paused, please press any key to
display sum of P Q') - pause
- disp(Z)
- disp('Again program is pausing for 5 sec')
- pause(5)
9Reading and storing file data
- There are many functions which are used to get
data from the files. - 1.load function To load variables/data in
workspace from the disk file - Different syntax are
- load load matlab.mat (default) file
- Load(filename) load complete file whose name
is given - Load(filename, x, y, z) load only
variables x, y, z of given file - Load filename x, y, z same as above
- Note-
- No extension with file name means .mat file
- If file name has extension other than (.mat) it
will be treated as ASCII data file - Load function is use only if data file contains
numeric data
10Reading and storing file data
- Exp
- gtgtedit abc.txt
- Write following and save it
- 3 4 5 7
- 7 8 0 9
- gtgtload abc.txt it will load this file in
workspace with a variable name abc, to check
it write abc - gtgtabc
- 3 4 5 7
- 7 8 0 9
- If we want to change the variable name write
following command - gtgttestload (abc.txt) now data abc.txt will
store in variable test
11Reading and storing file data
- 2.save function To save variables/data from
workspace to disk file - Different syntax are
- save save all workspace data in matlab.mat
file - save(filename) save complete workspace data
in specified file name - save(filename, x, y, z) save only
variables x, y, z in a file - save filename x, y, z same as above
- Note-
- No extension with file name means .mat file
- If file name has extension other than (.mat) it
will be treated as ASCII data file - To save variables to a directory other than
current directory, full pathname of the file has
to be specified.
12Reading and storing file data
- 3.dlmread function To read numeric text data
separated by character other than
space.(dlmgtdelimiter, by default delimiter is
comma ) - Different syntax are
- datadlmread(filename) read numeric data from
ASCII delimited file named filename - datadlmread(filename, delimiter) read
numeric data from ASCII delimited with other
delimiter - i.e.
- var_namedlmread(abc.txt, ) this will
read the data from file abc.txt till it
encounters delimiter. - For example see next slide
13Reading and storing file data
- 4.dlmwrite function To write numeric text data
separated by character other than space.
(dlmgtdelimiter, by default delimiter is comma ) - Different syntax are
- dlmwrite(filename,A) write matrix A on a
specified file name with default delimiter (,) - dlmwrite(filename, A, D) write matrix A
on a specified file name with default delimiter
D - i.e.
- gtgtA1 2 3 4 5 6 7 8 9
- gtgtdlmwrite(abcd.txt, A,D) this will write
matrix A on file abcd.txt with delimiter D.
Open this file See. - Now try
- gtgtBdlmread(abcd.txt,D)
14Reading and storing file data
- 5.textscan and textread functions If a text
file contains numeric as well as other
characters. The file need to be opened for read
operation using fopen command then read using
textscan command. - Different syntax are
- fidfopen(abc.txt, r) Open abc.dat file
for reading - var_nametextscan(fid, f c .) here f
for float, c for char etc - Note var_name will be cell array
- The command textread can be used to read the data
into separate variables. - a, b, c, dtextread(abc.txt, f c .)
- i.e.
- name, types, a, b, ctextread(abc.txt, s s
f f f)
15Output commands
- 1. Output may be formatted or unformatted
- Default format
- gtgta7
- a 7
- gtgtb1.01
- b 1.0100 4 digit after decimal
- gtgt2100.34
- c 2.1003e003 2.1003x103
- Format command to change default format
- gtgtxpi
- x 3.1416
- gtgtformat long similarly we can have other
format also see help - x
- 3.141592653589793
16Output commands
- disp function
- gtgtA1 2 3 4 to display variable
- gtgtdisp(A)
- 1 2
- 3 4
- gtgtdisp(The largest number is) to display a
message - The largest number is
17Low-level input-output functions
- There are a number of low-level file input-output
function in MATLAB taken from ANSI Standard C
Library. These are - 1. File opening and closing functions
- 2. Binary input-output functions
- 3. Formatted input-output functions
18Low-level input-output functions
- 1. File opening and closing functions
- fopen function To perform any operation on
file the first step is open it. Syntax are -
- fidfopen( filename, permission_code)
- where
- fidfile id
- permission_code read or write or append
- fid, message fopen(filename,
permission_code) - where
- message error msg if file doesnt open
properly otherwise it is empty string - fid, message fopen(filename,
permission_code, format) - where
- format optional string specifying the
numeric format of the data in the file
19Low-level input-output functions
- Standard file identifier values
-
- Note As more files are opened fids are allotted
in continuation and if a particular file is
closed, the fid assigned to it is released.
fid Meaning
-1 Fid opening fails
0 Standard input (keyboard)
1 Standard output (monitor screen)
2 Standard error
3 onwards Assign to file opened successfully
20Low-level input-output functions
- Permission code
-
- Note As more files are opened fids are allotted
in continuation and if a particular file is
closed, the fid assigned to it is released.
Permission text string Meaning
r Open a file(default) for reading, if not exist error occurs
r Open a file(default) for reading writing, if not exist error occurs
w Delete the contents of an existing file or create a new file, and open it for writing.
w Delete the contents of an existing file or create new file, and open it for reading and writing.
a Create and open a new file or open an existing file for writing, appending to the end of the file.
a Create and open new file or open an existing file for reading and writing, appending to the end of the file.
21Low-level input-output functions
- Other use of fopen function
- fidsfopen(all)
- where
- fidsa vector showing file ids of all opened
files - filename, permission_code, format fopen(fid)
-
- This function provieds filename,
permission_code format for open file specified
by fid
22Low-level input-output functions
- fclose function After performing operations on
file the last step is to close it. Syntax are -
- status fclose( fid)
- where
- status 0 if successfully closed
- -1 otherwise
- status fclose(all)
-
- It closes all open files except for standard
output(fid 1) standard error (fid 2) - Note Standard input, output error cant be
opened or closed with fopen fclose functions
23Low-level input-output functions
- Formatted input-output functions These are used
to print, scan or get data in desired format.
Different functions are - fprintf function
- fscanf function
- fgetl function
- fgets function
24Low-level input-output functions
- fprintf function Syntax is
- fprintf(fid, format, data)
- Exp Create a file having following code and rut
it. - x 0.11 y x exp(x)
- fid fopen('exp.txt','w')
- fprintf(fid,'6.2f 12.8f\n', y)
- fclose(fid)
- Now open the file exp.txt and see the data
- Note 1. Here 6.2f .
- it always starts with sign
- 6 total width of field
- 2 no of digits after decimal
- f fixed point
- 2. fprintf(6.2f 12.8f\n, y ) will print on
monitor, - here fid 0 i.e monitor
25Low-level input-output functions
In general format may be written as a.be Or
a.be always print with sign character
( or -) Or -a.be - left justified Or
0a.be pad zeros in starting Here a
field width b digits after decimal point e
conversion character (c for char, s for string,
d for int, e for exponential, f for fixed
point etc) Note 1. '6.2f 12.8f\n
here note the space b/w to formats 2. \n means
new line 3. fprintf displays only real
portion of complex value
26Low-level input-output functions
- fscanf function Syntax is
- fscanf(fid, format)
- And
- A, count fscanf(fid, format, sizeA)
- Where
- A variable to store data
- count no of values reads from the files
- sizeA size of matrix A
-
- Exp Read the data of previously created file
exp.txt. Create a file having following code
and rut it. - fid fopen('exp.txt')
- A fscanf(fid, 'g g', 2 inf) A is 2
row x inf column matrix - AA transpose to get the
original matrix - fclose(fid)
27Low-level input-output functions
- fgetl function Reads the next line of the
specified file, removing the newline characters. - Syntax is
-
- statementfgetl(fid)
-
- Exp Read and display the file fgetl.m one line
at a time - fid fopen('fgetl.m')
- tline fgetl(fid)
- while ischar(tline)
- disp(tline)
- tline fgetl(fid)
- end
- fclose(fid)
28Low-level input-output functions
- fgets function Reads the next line of the
specified file, including the newline characters - Syntax is
-
- statementfgets(fid)
-
- Exp Read and display the file fgetl.m one line
at a time - fid fopen('fgetl.m')
- tline fgets(fid)
- while ischar(tline)
- disp(tline)
- tline fgets(fid)
- end
- fclose(fid)
29Low-level input-output functions
- Binary input-output functions The formatted
input-output functions works with human readable
text in a file. This file is also called an ASCII
text file. These files require more disk space as
compared to binary files. - Different functions for binary files system are
- fwrite function
- fread function
30Low-level input-output functions
- fwrite function Syntax is
- countfwrite(fid, array, percision)
- Where
- count no of values (data) written to file
- fid file id
- array array of values to be written
- precision format of storing the values (char,
uchar, short, int, long, float, double)
31Low-level input-output functions
- Exp Please make a .m file of following code and
run it. - clear all clear
all variable in workspace - fidfopen('check.txt','r')
- A, count1fread(fid, 2,3, 'double') A is
double 2x3 matrix - B, count2fread(fid, 1, 'int') B is an
int constant - C, count3fread(fid, inf, 'char') C is a
char string - CC'
transpose of C - Cchar(C) Convert
numeric values into character string - fclose(fid
32Low-level input-output functions
- fread function Syntax is
- variable, countfread(fid, size, percision)
- Where
- variable values to be read from file
- size dimensions of data to be read
- Note To read binary data from a file correctly,
it must be know how it was written
33Low-level input-output functions
Exp Please make a .m file of following code and
run it. a2 3 6 3 5 7 b105 c'IPL has
started' fidfopen('check.txt',r') A,
count1fread(fid, 2,3, 'double') A is
double 2x3 matrix B, count2fread(fid,
1, 'int') B is an int constant C,
count3fread(fid, inf, 'char') C is a char
string fclose(fid)
34