Experiment # 3
Introduction to MATLAB
3.1 Objective
i. To get familiarize with input/output of variables.
ii. To get familiarize with flow control in MATLAB.
3.2 Characters and Text
Enter text into MATLAB using single quotes. For example,
>> S = 'Hello'
The result is not the same kind of numeric matrix or array we have been dealing with up to now.
The string is actually a vector whose components are the numeric codes for the characters (the
first 127 codes in ASCII). The length of S is the number of characters. It is a 1-by-5-character
array. A quote within the string is indicated by two quotes.
Concatenation with square brackets joins text variables together into larger strings. For
example,
>> h = ['MAT', 'LAB']
joins the strings horizontally and produces,
h=
MATLAB
and the statement
>> v = ['MAT'; 'LAB']
joins the strings vertically and produces,
v=
MAT
LAB
Note that both words in v have to have the same length. The resulting arrays are both
character arrays; h is 1-by-6 and v is 2-by-3.
3.2.1 Some String Function
Function Description
char (x) converts the array x that contains positive integers representing
character codes into a MATLAB character array (the first 127
>> char(100) codes in ASCII).
ans =
d
>> char([73 82 65
81]) ans =
IRAQ
Function Description
double(s) converts the character array to a numeric matrix containing
floating point representations of the ASCII codes for each
>> double('z') character.
ans =
122
>> double('ali')
ans =
97 108 105
strcat(S1,S2,...) joins S1,S2,...variables horizontally together into larger
string.
>>strcat('Hello',' Ali') ans =
Hello Ali
strvcat(S1,S2,...) joins S1,S2,... variables vertically together into larger string.
>> strvcat ('Hello',
'Hi', 'Bye') ans =
Hello
Hi
Bye
s = num2str(x) converts the variable x into a string representation s.
>> num2str(20)
ans =
% as a string, not a number
x = str2num(s) converts character array representation of a matrix of
numbers to a numeric matrix.
>> str2num('20')
ans =
20
error (Msg) displays the error message in the string (Msg), and causes
an error exit from the currently executing M-file to the
keyboard.
lower(A) Converts any uppercase characters in A to the
corresponding lowercase character and leaves all other
characters unchanged.
Function Description
upper(x) Converts any lower case characters in A to the corresponding upper case
character and leaves all other characters unchanged
Note
The printable characters in the basic ASCII character set are represented by the integers 32:127.
(The integers less than 32 represent nonprintable control characters). Try >> char(33:127)
3.3 Input of Variable
To enter matrix or vector or single element:
>> x=input('parameter= ')
parameter= 2
x=
>> x=input('parameter= ')
parameter= [2 4 6]
x=246
>> x=input('parameter= ')
parameter= [1 2 3;4 5 6]
x=123
456
To enter text:
3.4 Output of Variable
disp ( x )
displays the array ( x ), without printing the array name. In all other ways it's the same as leaving
the semicolon off an expression except that empty arrays don't display.
If ( x ) is a string, the text is displayed.
>> x=[1 2 3];
>> x
x=
123
>> disp(x)
123
Example:
>> a=6;
>> b=a;
>> s='Ahmed has ';
>> w='Ali has ';
>> t=' Dinars';
>>disp([ s num2str(a) t]);
>>disp([ w num2str(b) t]);
the execution result is:
Ahmed has 6 Dinars
Ali has 6 Dinars
3.5 M-File
An M-File is an external file that contains a sequence of MATLAB statements. By typing the
filename in the Command Window, subsequent MATLAB input is obtained from the file. M-
Files have a filename extension of " .m " and can be created or modified by using
Editor/Debugger Window.
3.5.1 Script Files
You need to save the program if you want to use it again later. To save the contents of the
Editor, select File → Save from the Editor menu bar. Under Save file as, select a directory and
enter a filename, which must have the extension .m, in the File name: box (e.g., faez.m). Click
Save. The Editor window now has the title faez.m If you make subsequent changes to faez.m an
asterisk appears next to its name at the top of the Editor until you save the changes.
A MATLAB program saved from the Editor with the extension .m is called a script file, or
simply a script. (MATLAB function files also have the extension.m. We therefore refer to both
script and function files generally as M-files.).
The special significances of a script file are that: -
1. if you enter its name at the command-line prompt, MATLAB carries out each
statement in it as if it were entered at the prompt.
2. Scripts M-file does not accept input arguments or return output arguments. They
operate on data in the workspace.
3. The rules for script file names are the same as those for MATLAB variable
names.
3.5.2 Function Files
MATLAB enables you to create your own function M-files. A function M-file is like a script file
in that it also has an .m extension. However, it differs from a script file in that it communicates
with the MATLAB workspace only through specially designated input and output arguments.
* Functions operate on variables within their own workspace, separate from the
workspace you access at the MATLAB command prompt.
General form of a function: A function M-file filename.m has the following general form:
Note:
inarg1, inarg2,... are the input variables to the function filename.m
outarg1, outarg2,... are the output variables from the function filename.m function The
function file must start with the keyword function (in the function definition line).
Example:
3.6 Exercise
1. If x=[1 5 9; 2 7 4], then
a) display the last two elements by using disp command.
b) display the sum of each row as show below
The sum of 1st row =
The sum of 2nd row =
2- Write a program in M-File to read 3 x 3 Matrix, then display the diagonal of matrix as
shown below:
The Diagonal of This Matrix = [ ]
3- Write a program to read a string, then replace each character in the string with its
following character in ASCII code.
4- The Table shown below lists the degrees of three students, Write a program in M-file
to read these degrees and calculate the average degree for each student.
Name Mathematics Electric Circuits Communication
Ahmed 80 80 80
Waleed 75 80 70
Hasan 80 90 85
Then display results as shown below,
5- Write a group of statements that carry out the same action of upper and lower
functions.
3.7 Flow Control
Computer programming languages offer features that allow you to control the flow of command
execution based on decision making structures. MATLAB has several flow control
constructions:
if statement.
switch and case statement.
for statement.
while statement.
break statement.
3.7.1 if statement
The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The optional elseif and else keywords provide for the execution of alternate
groups of statements. An end keyword, which matches the if, terminates the last group of
statements.
The general form of if statement is:
if expression 1
group of statements 1
elseif expression 2
group of statements 2
else expression 3
group of statements 3
end
It is important to understand how relational operators and if statements work with matrices.
When you want to check for equality between two variables, you might use
if A = = B
This is legal MATLAB code, and does what you expect when A and B are scalars. But when A
and B are matrices, A = = B does not test if they are equal, it tests Where they are equal; the
result is another matrix of 0’s and 1’s showing element-by-element equality. In fact, if A and B
are not the same size, then A = = B is an error. The proper way to check for equality between
two matrix is to use the isequal function,
if isequal(A,B)
Example:
A=input('A=');
B=input('B=');
if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error ('Unexpected situation')
end
3.7.2 switch and case statement
The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching case
is executed. There must always be an end to match the switch. If the first case statement is true,
the other case statements do not execute.
The general form of switch statement is:
switch expression
case 0
statements 0
case 1
statements 1
otherwise
statements 3
end
Example
3.7.3 for statement
The for loop repeats a group of statements a fixed, predetermined number of times. The general
form of for statement is:
for variable = initial value: step size: final value statement
...
statement
end
Example:
A for loop cannot be terminated by reassigning the loop variable within the for loop:
3.7.4 while Statement
repeat statements an indefinite number of times under control of a logical condition. A
matching end delineates the statements.
The general form of while statement is:
while expression
statement
...
statement
end
Example: Here is a complete program, illustrating while, if, else, and end, that uses interval
bisection method to find a zero of a polynomial.
3.7.5 break
Terminate execution of while or for loop. In nested loops, break exits from the innermost loop
only. If break is executed in an IF, SWITCH-CASE statement, it terminates the statement at
that point.
3.7.6 Continue
passes control to the next iteration of FOR or WHILE loop in which it appears, skipping any
remaining statements in the body of the FOR or WHILE loop.
Example:
we can modify the previous example by using break command.
Example: Without using the max command, find the maximum value of matrix (a)
where a =[11 3 14;8 6 2;10 13 1]
3.8 Exercises
1. The value of s could be calculated from the equation below:
write a MATLAB program in M-File to do the following steps:-
a) input the value of x, y, z
b) caluclate s
c) print the output as shown below
x=...
y=...
z=...
s=...
2- Write a program to find the current I in the circuit shown
below
a) By using conditional statements.
b) Without using any conditional statements.