5 Input Output Statements

advertisement
MATLAB
Input-Output Statements
Nafees Ahmed
Asstt. Professor, EE Deptt
DIT, DehraDun
Introduction
 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
Data Input
• 1.
Assign data to variables through an assignment statement
>>x=2;
>>y=34.2;
>>name=“Raheel Sufyaan”;
or
>>x=2; y=34.2; name=“Raheel Sufyaan”;
Data Input
• 2.
I.
II.
III.
IV.
Input data from Keyboard (Interactive input)
Input Function
Keyboard Command
menu function
pause command
Data Input
I. Input Function : See different version of this function
>>r=input(‘Enter radius in meters:’)
Enter radius in meters:56
r=
56
Enter radius in meters: ’ninety six’
r=
ninety six
%r will become integer
%r will become string , Note: ‘ ‘ compulsory
>>r=input(‘what is your father’s name:’, ’s’)
what is your father’s name: Nafees Ahmed
r=
Nafees Ahmed
%r string,
% Note: ‘ ‘ not required
Data 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
1. Check the intermediate results in the program
2. Make changes in variables value if required
3. Add new MATLAB commands in the program
Exp: Make a .m file for the following code and run it
A=10;
B=16;
X=A+B;
Y=X/2;
Keyboard
Z=A-B
%check the value of Y and change Y=10, after finishing write
%‘return’ command, it will execute rest program
Data Input
III. ‘menu’ function
for pictorial selection. Syntax is
I=menu(‘title’, ‘option1’, ‘option2’,……..)
Exp: Make a .m file for the following code and run it
i=menu('Select your favorite name','Teenu','Sumbul','Humera');
if i==1
disp('Teenu is your wife')
elseif i==2
disp('Sumbul is yr sis-in-low')
elseif i==3
disp('Humera is yr sis-in-low')
else
disp('Bewakoof kuch to select karo')
end
Data 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
P=[1 2; 3 4]; Q=[5 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)
Z=P+Q;
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)
Reading 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:1. No extension with file name means .mat file
2. If file name has extension other than (.mat) it will be treated as ASCII
data file
3. Load function is use only if data file contains numeric data
Reading and storing file data
Exp:
>>edit abc.txt
Write following and save it
1 3 4
5
7
6 7 8
0
9
>>load abc.txt
%it will load this file in workspace with a variable
%name abc, to check it write abc
>>abc
1 3 4
5
7
6 7 8
0
9
If we want to change the variable name write following command
>>test=load (‘abc.txt’) %now data ‘abc.txt’ will store in variable ‘test’
Reading 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:1. No extension with file name means .mat file
2. If file name has extension other than (.mat) it will be treated as ASCII
data file
3. To save variables to a directory other than current directory, full
pathname of the file has to be specified.
Reading and storing file data
3.’dlmread’ function: To read numeric text data separated by character other
than space.(dlm=>delimiter, by default delimiter is comma )
Different syntax are
data=dlmread(‘filename’)
data=dlmread(‘filename’, delimiter)
i.e.
var_name=dlmread(‘abc.txt’, ‘;’)
For example see next slide
%read numeric data from ASCII delimited file named filename
%read numeric data from ASCII delimited with other delimiter
% this will read the data from file abc.txt till it encounters ‘;’ delimiter.
Reading and storing file data
4.’dlmwrite’ function: To write numeric text data separated by character other
than space. (dlm=>delimiter, by default delimiter is comma )
Different syntax are
dlmwrite(‘filename’,A)
dlmwrite(‘filename’, A, ‘D’)
%write matrix ‘A’ on a specified file name with default delimiter (,)
% write matrix ‘A’ on a specified file name with default delimiter ‘D’
i.e.
>>A=[1 2 3; 4 5 6; 7 8 9]
>>dlmwrite(‘abcd.txt’, A,‘D’) % this will write matrix A on file abcd.txt with delimiter ‘D’. Open this file & See.
Now try
>>B=dlmread(‘abcd.txt’,’D’)
Reading 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
fid=fopen(‘abc.txt’, ’r’)
var_name=textscan(fid, ‘%f %c …….’)
%Open abc.dat file for reading
%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, d]=textread(‘abc.txt”, ‘%f %c …….’)
i.e.
[name, types, a, b, c]=textread(‘abc.txt’, ’%s %s %f %f %f’)
Output commands
1. Output may be formatted or unformatted
• Default format :
>>a=7
a= 7
>>b=1.01
b= 1.0100
%4 digit after decimal
>>2100.34
c= 2.1003e+003
%2.1003x103
• Format command to change default format
>>x=pi
x = 3.1416
>>format long
%similarly we can have other format also see help
x=
3.141592653589793
Output commands
2. ‘disp’ function
>>A=[1 2; 3 4];
>>disp(A)
1 2
3 4
>>disp(‘The largest number is;’)
The largest number is
% to display variable
%to display a message
Low-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
Low-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
•
•
•
fid=fopen( filename, permission_code)
where
fid=file id
permission_code = read or write or append
[fid, message] = fopen(filename, permission_code)
where
message = error msg if file doesn’t 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
Low-level input-output functions
 Standard file identifier values
Note:
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
As more files are opened fids are allotted in continuation
and if a particular file is closed, the fid assigned to it is
released.
Low-level input-output functions
 Permission code
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
Note:
a+
Create and open a new file or open an existing file for
As more files
are opened fids are allotted in continuation
writing, appending to the end of the file.
and if a particular file is closed, the fid assigned to it is
released.Create and open new file or open an existing file for
reading and writing, appending to the end of the file.
Low-level input-output functions
 Other use of ‘fopen’ function:
•
fids=fopen(‘all’)
where
fids=a 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
Low-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
=-1
if successfully closed
otherwise
status = fclose(‘all’)
It closes all open files except for standard output(fid = 1) &
standard error (fid = 2)
Note:
Standard input, output & error can’t be opened or closed
with
fopen & fclose functions
Low-level input-output functions
2. Formatted input-output functions: These are used to print,
scan or get data in desired format. Different functions are
i.
ii.
iii.
iv.
fprintf function
fscanf function
fgetl function
fgets function
Low-level input-output functions
i.
‘fprintf ‘ function: Syntax is
fprintf(fid, format, data)
Exp: Create a file having following code and rut it.
x = 0:.1:1; 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
Low-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
Low-level input-output functions
ii.
‘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
A=A’
% transpose to get the original matrix
fclose(fid);
Low-level input-output functions
iii. ‘fgetl ‘ function: Reads the next line of the specified file,
removing the newline characters.
Syntax is
statement=fgetl(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);
Low-level input-output functions
iv. ‘fgets ‘ function: Reads the next line of the specified file,
including the newline characters
Syntax is
statement=fgets(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);
Low-level input-output functions
3. 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
i.
ii.
‘fwrite’ function
‘fread’ function
Low-level input-output functions
i.
‘fwrite’ function: Syntax is
count=fwrite(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)
Low-level input-output functions
Exp: Please make a .m file of following code and run it.
clear all
%clear all variable in workspace
fid=fopen('check.txt','r');
[A, count1]=fread(fid, [2,3], 'double')
%A is ‘double’ 2x3 matrix
[B, count2]=fread(fid, [1], 'int')
%B is an int constant
[C, count3]=fread(fid, [inf], 'char')
%C is a char string
C=C'
%transpose of C
C=char(C)
%Convert numeric values into character string
fclose(fid
Low-level input-output functions
i.
‘fread’ function: Syntax is
[variable, count]=fread(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
Low-level input-output functions
Exp: Please make a .m file of following code and run it.
a=[2 3 6; 3 5 7];
b=105;
c='IPL has started';
fid=fopen('check.txt',‘r');
[A, count1]=fread(fid, [2,3], 'double') %A is ‘double’ 2x3 matrix
[B, count2]=fread(fid, [1], 'int')
%B is an int constant
[C, count3]=fread(fid, [inf], 'char')
fclose(fid)
%C is a char string
=
Download