You are on page 1of 111

1

MATLAB fundamentals of programming

INDEX

TOPICS PAGE.NO

1. INTRODUCTION 3-3
1.1 HISTORY 3-3
1.2 ALTERNATIVES 3-3
1.3 MATLAB FUNCTIONING AND WINDOWS 3-8
2. INPUTS IN MATLAB 8-8
3. ERRORS IN MATLAB 9-9
4. MATLAB PROGRAM FILES 9-9
5. RULES FOR NAMING A FILE 9-9
6. KEYWORDS 10-10
7. DATA TYPES 10-11
8. OPERATORS 11-11
8.1 CLASSIFICATION BASED ON NO.OF OPERANDS 11-12
8.2 CLASSIFICATION BASED ON TYPE OF OPERATION 12-25
9 CONDITIONAL STATEMENTS 26-28
10 SWITCH STATEMENTS 28-31
11 LOOPS
11.1 FOR LOOP 31-32
11.2 WHILE LOOP 32-33
12 BREAK AND CONTINUE IN LOOPS
12.1 BREAK AND CONTINUE IN FOR LOOP 33-34
12.2 BREAK AND CONTINUE IN WHILE LOOP 34-36
13 NESTED LOOPS 36-37
14 BREAK AND CONTINUE IN NESTED LOOPS
14.1 BREAK IN NESTED LOOP 38-39
14.2 CONTINUE IN NESTED LOOP 39-40
15 FUNCTIONS 41-43

SV MATLAB Solutions 9652458410 Anji Reddy


2
MATLAB fundamentals of programming
16 METHODS FOR ENTERING DATA INTO THE FILE
16.1 DIRECT ASSIGNING 43-43
16.2 PRE-DEFINED FUNCTIONS 43-44
16.3 LOADING FROM OTHER FILES 44-44
17 WORKING WITH MATRICES 45-46
18 GRAPHIC RELATED FUNCTIONS 47-55
19 GRAPHICAL USER INTERFACE 56-57
19.1 OVERVIEW OF GUI 57-58
19.2 GRAPHICAL OBJECTS 58-59
19.3 PROPERTIES OF OBJECT 59-60
19.4 HANDLING AN OBJECT 61-61
19.5 PREVIOUS VERSIONS 61-62
19.6 BUILDING SAMPLE GUI 62-72
19.7 EXAMPLE PROGRAMS 73-92
20 MATLAB INSTALLATION 92-105
21 GENERAL QUESTIONS IN MATLAB 106-112

SV MATLAB Solutions 9652458410 Anji Reddy


3
MATLAB fundamentals of programming

1. INTRODUCTION

MATLAB (matrix laboratory) is. a numerical computing environment and fourth-generation


programming language. Developed by Math Works

1.1. HISTORY

Cleve Moler, the chairman of the computer science department at the University of New Mexico,
started developing MATLAB in the late 1970s. He designed it to give his students access to
LINPACK and EISPACK without them having to learn Fortran. It soon spread to other
universities and found a strong audience within the applied mathematics community. Jack Little,
an engineer, was exposed to it during a visit Moler made to Stanford University in 1983.
Recognizing its commercial potential, he joined with Moler and Steve Bangert. They rewrote
MATLAB in C and founded MathWorks in 1984 to continue its development. These rewritten
libraries were known as JACKPAC. In 2000, MATLAB was rewritten to use a newer set of
libraries for matrix manipulation, LAPACK.

MATLAB was first adopted by researchers and practitioners in control engineering, Little's
specialty, but quickly spread to many other domains. It is now also used in education, in
particular the teaching of linear algebra and numerical analysis, and is popular amongst scientists
involved in image processing.

1.2. ALTERNATIVES

MATLAB has a number of competitors. Commercial competitors include Mathematica, Maple,


NAG, and IDL. There are also free open source alternatives to MATLAB, in particular GNU
Octave, FreeMat, and Scilab which are intended to be mostly compatible with the MATLAB
language.

1.3. MATLAB FUNCTIONING AND WINDOWS

SV MATLAB Solutions 9652458410 Anji Reddy


4
MATLAB fundamentals of programming
MATLAB allows matrix manipulations, plotting of functions and data, implementation of
algorithms, creation of user interfaces, and interfacing with programs written in other languages,
including C, C++, Java, and Fortran.

Although MATLAB is intended primarily for numerical computing, an optional toolbox uses the
MuPAD symbolic engine, allowing access to symbolic computing capabilities. An additional
package, Simulink, adds graphical multi-domain simulation and Model-Based Design for
dynamic and embedded systems.

In 2004, MATLAB had around one million users across industry and academia. MATLAB users
come from various backgrounds of engineering, science, and economics. MATLAB is widely
used in academic and research institutions as well as industrial enterprises.

 windows in matlab

SV MATLAB Solutions 9652458410 Anji Reddy


5
MATLAB fundamentals of programming

Command history: It remembers all the commands used in command window

Example : pwd, clc, date etc.,

Work space: work space stores all the variables used in the program and it stores in the
following format.

Example: if we take in command window as a= [1 4 5


234
0 7 9]

variable name class min max

A 3*3double 1 9

SV MATLAB Solutions 9652458410 Anji Reddy


6
MATLAB fundamentals of programming

Current folder: lists all the files present in the current folder. ‘m’ is the extension for matlab files
or programs.

Example: main.m

We can see the execution of the file by typing file name in command window.

SV MATLAB Solutions 9652458410 Anji Reddy


7
MATLAB fundamentals of programming

Variable editor: Opens when double clicked on the variable name.

If values of minimum and maximum in a variable editor are changed,then those are also
modified automatically in workspace.

SV MATLAB Solutions 9652458410 Anji Reddy


8
MATLAB fundamentals of programming

2. INPUTS IN MATLAB

There are 2 types of inputs in matlab they are:

1. Static or direct input


In static we directly provide value for a variable in the program file.
Example: a=10
2. Dynamic input

In dynamic input, values for variables are provided during run time or execution on the
command window. The state of the command window is known at the left bottom corner of the
window.

Example: a=input(‘enter a value’)


3. Graphical input
Here the resultant for graphical input is observed in figure window.
Example: display(a)

SV MATLAB Solutions 9652458410 Anji Reddy


9
MATLAB fundamentals of programming
3. ERRORS IN MATLAB

1. Syntax error
Can be caused due to omitting operators in an expression.
Example: b(a+c)  error expression
b*(a+c)  correct expression
2. Execution time errors/run time errors
Can be caused while execution or compilation.

 In matlab compilation and execution are done at a time line by line. Untill and
unless you clear the errors in first line you can’t proceed with further lines and so
on..
 In MAT LAB no need to terminate the statements with semi colon(;).
 No need to declare any variables to use them in the program.

4. MAT LAB PROGRAM FILES:

1. Script
We write programs in script or edit file. Procedure to start with the edit file is
FILE NEW SCRIPT (or) edit(type edit in command window) (or) control-N
2. Function
Function calls are defined in function file.procedure to start with function file is
FILE NEW FUNCTION

5. RULES FOR NAMING A FILE

1. File name can contain alphabets, digits, under scores.


2. File name should not start with digit or underscore.
3. Spaces are not allowed between file names.
4. Keywords should not be used for naming a file.

SV MATLAB Solutions 9652458410 Anji Reddy


10
MATLAB fundamentals of programming
6. KEYWORDS

Keywords are written in lower case only. they cannot be used as variable names.

Example: if, switch, for etc.,

7. DATA TYPES

There are 10 Data types in mat lab that reveals two different informations. They are

 The memory that is provided for a variable.


 The data that is stored in the variable.
1. Char : each character is provided with 2 bytes of memory.
Eg: for a word ‘hello’ the memory provided is 10 bytes because there total 5 letters the
word.
2. Uint8 : here memory is 1 byte I,e 8 bits.data is stored in all the 8 bits.unsigned integer
refers to all positive values.
1 2 3 4 5 6 7 8

3. Int8 : int 8 has 1 byte of memory in which 1st bit or most significant bit is reserved as
sign bit.positive or negative sign of data is indicated with 1 or 0.
1 2 3 4 5 6 7 8

4. Uint16: memory is 2 bytes. memory allocation is similar to uint8.


msb

5. Int16: memory is 2 bytes(16 bits in which msb is sign bit). memory allocation is similar
to int8
msb

6. Uint32: memory is 4 bytes(32 bits). memory allocation is similar to uint8

SV MATLAB Solutions 9652458410 Anji Reddy


11
MATLAB fundamentals of programming
7. Int32: memory is 4 bytes (32 bits in which msb is sign bit). memory allocation is similar
to int8
msb

8. Single: here data is stored in the form of exponential and mantissa.


Eg : 3.14 = 314*10^(-2) where 314 is mantissa and -2 is exponential.memory allocated is
4 bytes and is divided as follows.
Sign of mantessa mantessa Sign of exponent exponent
1bit 23bits 1bit 7bits
9. Double : memory allocation is similar to single but memory is 8 bytes
Sign of mantessa mantessa Sign of exponent exponent
1bit 52bits 1bit 10bits

10. Logical: memory is only 1 byte and is used to store logical result of a function i,e 0 or 1.

8. OPERATORS

Classification of operators is based on number of operands and type of operation.

8.1 Classification based on number of operands

1. unary operators : we use only one operand and one operator to perform an operation.

Example: a’(transpose of a)

~a(not a)

2. binary operators : we use two operands and one operator

example: all arithmetic operations like a+b, a-b, a*b

SV MATLAB Solutions 9652458410 Anji Reddy


12
MATLAB fundamentals of programming
8.2 Classification based type of operation

1. Arithmetic operators

All the arithmetic operations can be performed between teo scalars,two matrices and a scalar
and a matrix.

 Addition operator (+)


Example:

clc
clear all
a=[1 2 3;3 4 5;5 6 7];
b=[4];
c=a+b;
display(c)

Result:

c=

5 6 7

7 8 9

9 10 11

 Subtraction operator(-)
Example:

clc
clear all
a=[1 2 3;3 4 5;5 6 7];
b=[4];
c=a-b;
display(c)

SV MATLAB Solutions 9652458410 Anji Reddy


13
MATLAB fundamentals of programming

Result:

c=
-3 -2 -1
-1 0 1

1 2 3

 Multiplication operator(*)
Example:

clc
clear all
a=[1 2 3;3 4 5;5 6 7];
b=[4 5 6;7 8 9;0 3 2];
c=a*b;
display(c)

Result:

c=

18 30 30

40 62 64

62 94 98

 array multiplication operator(.*)


Example :

clc
clear all
a=[1 2 3;4 5 6;7 8 9];
b=[2 3 1;5 4 3;9 0 8];
c=a.*b;

SV MATLAB Solutions 9652458410 Anji Reddy


14
MATLAB fundamentals of programming
display(c)

result :
c=

2 6 3
20 20 18
63 0 72

 Left division(/)

Example:

clc
clear all
a=[7];
b=[4];
c=a/b;
display(c)

Result:

c = 1.7500

 right division(\)
Example:

clc
clear all
a=[7];
b=[4];
c=a\b;
display(c)

Results:

SV MATLAB Solutions 9652458410 Anji Reddy


15
MATLAB fundamentals of programming
c = 0.5714

 (array division(./)

Example :

clc
clear all
a=[1 2 3;4 5 6;7 8 9];
b=2;
c=a./b;
display(c)

result :

c=

0.5000 1.0000 1.5000

2.0000 2.5000 3.0000

3.5000 4.0000 4.5000

 Power(^)
Example:

clc
clear all
a=10;
b=4;
c=a^b;
display(c)

Result:
c=

10000

SV MATLAB Solutions 9652458410 Anji Reddy


16
MATLAB fundamentals of programming

 Element wise power(.^)


Example:

clc
clear all
a=[1 2 3;4 5 6;7 8 9];
b=2;
c=a.^b;
display(c)

result:
c=

1 4 9
16 25 36
49 64 81

 Transpose(')
Example:

clc
clear all
a=[1 2 3;4 5 6;7 8 9];
c=a';
display(c)

result:

c=

1 4 7
2 5 8

3 6 9

 complex conjugate of a transpose(.')

SV MATLAB Solutions 9652458410 Anji Reddy


17
MATLAB fundamentals of programming
Example:

clc
clear all
a=[1+i 2-i 3;4 5+i 6;7 8 9-i];
c=a.';
display(c)

Result:
c=

1.0000 + 1.0000i 4.0000 7.0000


2.0000 - 1.0000i 5.0000 + 1.0000i 8.0000
3.0000 6.0000 9.0000 - 1.0000i

2. Relational operators : result of relational operators will be in logical form. And these
operators can be used between 2 scalars, 2 matrices or a scalar and a matrix.

 greater than(>)
Example :
clc
clear all
a=[1 2 3;4 5 6;7 8 9];
b=[1 0 9;5 4 3;6 7 1];
c=a>b;
display(c)

result:
c=

0 1 0

0 1 1
1 1 1

 less than(<)

SV MATLAB Solutions 9652458410 Anji Reddy


18
MATLAB fundamentals of programming
Example:
clc
clear all
a=[1 2 3;4 5 6;7 8 9];
b=[6];
c=a<b;
display(c)

Result:
c=

1 1 1
1 1 0
0 0 0

 greater or equal to(>=)


Example:
clc
clear all
a=[1];
b=[6];
c=a>=b;
display(c)

Result:
c=0

 less or equal to(<=)


Example:
clc
clear all
a=[1 2 3;4 5 6;7 8 9];
b=[1 0 9;5 4 3;6 7 1];
c=a<=b;
display(c)

SV MATLAB Solutions 9652458410 Anji Reddy


19
MATLAB fundamentals of programming
Result:
c=

1 0 1

1 0 0
0 0 0

 equal to(==)
Example:
clc
clear all
a=[1 2 3;4 5 6;7 8 9];
b=[1 0 9;5 4 3;6 8 1];
c=a==b;
display(c)

Result:
c=

1 0 0
0 0 0
0 1 0

 not equal to(~=)


Example:
clc
clear all
a=[1 5 3;4 5 6;7 8 5];
b=[5];
c=a~=b;
display(c)

SV MATLAB Solutions 9652458410 Anji Reddy


20
MATLAB fundamentals of programming
Result:
c=

1 0 1

1 0 1
1 1 0

3. Logical operators
 logical AND(&)
Example:

clc
clear all
a=[1 0 1;0 1 1;1 0 0];
b=[1 0 0;1 1 1;1 1 0];
c=a&b;
display(c)

Result:

c=

1 0 0
0 1 1
1 0 0

 logical OR( | )
Example:

clc
clear all
a=[1 0 1;0 1 1;1 0 0];
b=[1 0 0;1 1 1;1 1 0];
c=a|b;
display(c)

SV MATLAB Solutions 9652458410 Anji Reddy


21
MATLAB fundamentals of programming

Result:

c=

1 0 1
1 1 1
1 1 0
 logical NOT(~)
Example:

clc
clear all
a=[1 0 1;0 1 1;1 0 0];
c= ~a;
display(c)

Result:

c=

0 1 0

1 0 0

0 1 1
4. Assignment operator
 Assignment(=)
Example:

clc
clear all
a=6;
b=9;
a=b;
display(a)

SV MATLAB Solutions 9652458410 Anji Reddy


22
MATLAB fundamentals of programming

Result:

a=9

5. Semicolon operator(;)

Semicolon is has two applications in matlab. Former is it is used as row saperator in matrix
entries and secondly it is used to suppress the output at command window. The assignment
statements are displayed on command window if they are not suppressed. To avoid that we
suppress those statements with semicocolon and write display statements wherever required.

Example:

clc
clear all
c=[12 23 34;5 67 45;23 46 89];
display(c)

Result:

c=

12 23 34
5 67 45
23 46 89

6. Colon operator (:) : colon operator is used for generation and accessing values from a
matrix.

Example for sequence generation:

clc
clear all
t=0:2:20;
x=sin(t);

SV MATLAB Solutions 9652458410 Anji Reddy


23
MATLAB fundamentals of programming
plot(t,x)

result

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8
0 2 4 6 8 10 12 14 16 18 20

Example:

clc
clear all
a=[1 2 3 4 5;5 6 7 8 9;10 11 12 13 14;15 16 17 18 19;3 45 12 13 78];
b=a(1,1:5)
c=a(2:4,1:3)
d=a(1:4:5,1:3:4)
e=a(end-2,end-3)

Result:
b= 1 2 3 4 5
c=
5 6 7

10 11 12
15 16 17
d=

SV MATLAB Solutions 9652458410 Anji Reddy


24
MATLAB fundamentals of programming
1 4
3 13
e =11
7. Other operator(type casting): in typecasting we can change the type of any variable.

Example:

clc
clear all
a=[1 2 3 4 5;5 6 7 8 9;10 11 12 13 14;15 16 17 18 19;3 45 12 13 78];
b=uint8(a)

Result:
b=

1 2 3 4 5
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
3 45 12 13 78
Size and data type of a variable are stored in variable editor in workspace.

SV MATLAB Solutions 9652458410 Anji Reddy


25
MATLAB fundamentals of programming

SV MATLAB Solutions 9652458410 Anji Reddy


26
MATLAB fundamentals of programming
9 CONDITIONAL STATEMENTS

There are types of conditional statements

 Simple if
Syntax:

if condition
----
----
-----
End
Example:
clc
clear all
a=input('enter a value');
b=input('enter b value');
if a>b
display('a is greater')
end

 If-else
Syntax:

if condition
----
----
-----
else
----
----
end
example

clc
clear all
a=input('enter a value');
b=input('enter b value');
if a>b
display('a is greater')
else
display('b is greater')
end

SV MATLAB Solutions 9652458410 Anji Reddy


27
MATLAB fundamentals of programming

 Elseif
Syntax:

if condition
----
----
-----
elseif condition
----
----
else
---
---
end
example:

clc
clear all
a=input('enter a value');
b=input('enter b value');
if a>b
display('a is greater')
elseif b>a
display('b is greater')
else
display('a and b are equal')
end

 Nested if
Syntax:

if condition
----
----
if condition
----
----
end

end
example:

SV MATLAB Solutions 9652458410 Anji Reddy


28
MATLAB fundamentals of programming
clc
clear all
x=input('enter x value');
if x < 0
display('sign = -1')
else
if x == 0
display('sign = 0')
else
display('sign = 1')
end
end

10.SWITCH STATEMENTS

In these statements the program can be executed by choosing different parts of it.

Example1

clc
clear all
dsply=input('enter choice');
switch dsply
case 1
display('case 1')
case 2
display('case2')

case 3
display('case3')
otherwise
display('wrong choice')
end

example2

clc
clear all
t=0:0.5:20;
dsply=input('enter choice');
SV MATLAB Solutions 9652458410 Anji Reddy
29
MATLAB fundamentals of programming
switch dsply
case 1
x=sin(t);
plot(t,x)
title('sine wave')
xlabel('time period')
ylabel('amplitude')

case 2
y=sin(t);
plot(t,y)
title('cos wave')
xlabel('time period')
ylabel('amplitude')
case 3
z=tan(t);
plot(t,z)
title('tan wave')
xlabel('time period')
ylabel('amplitude')
otherwise
display('wrong choice')
end

result

enter choice 1

sine wave
1

0.5
amplitude

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20
time period

SV MATLAB Solutions 9652458410 Anji Reddy


30
MATLAB fundamentals of programming
enter choice 2

cos wave
1

0.5
amplitude

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20
time period

enter choice 3

tan wave
50

-50
amplitude

-100

-150

-200

-250
0 2 4 6 8 10 12 14 16 18 20
time period

enter choice 4

SV MATLAB Solutions 9652458410 Anji Reddy


31
MATLAB fundamentals of programming
wrong choice

9. LOOPS

Loops are used to repeat a set of statements until a condition fails or for a particular number of
times. There are two loops in matlab.

11.1 .For loop: in for loop number of iterations are known.

Syntax:

For (expression)

_____

____

End

Example:

clc
clear all
for i=1:10
display(a)
end

as a result we get display of numbers from 1 to 10.so number of iterations are 10.

11.2. While loop: in while loop number of iterations are unknown

Syntax:

while (condition)

_____

____

End

SV MATLAB Solutions 9652458410 Anji Reddy


32
MATLAB fundamentals of programming
Example:

clc
clear all
a=input('enter a value');
b=input('enter b value');
while a<b
display(a)
display(b)
a=a+2;
b=b-3;
end

execution

enter a value30

enter b value40

a = 30

b = 40

a = 32

b = 37

10. BREAK AND CONTINUE IN


LOOPS

Break  when break statement is used in loop,then the execution comes out of the loop.

Continue  when continue is used in the loop,then execution shifts to initial step.

12.1 BREAK AND CONTINUE IN FOR LOOP

 Break in for loop

program

SV MATLAB Solutions 9652458410 Anji Reddy


33
MATLAB fundamentals of programming
clc
clear all
for a=1:10
if a==5
break
end
display(a)
end

execution

a =1

a=2

a=3

a= 4

 continue in for loop

program

clc
clear all
for a=1:10
if a==5
continue
end
display(a)
end

execution

a=1

a=2

a=3

a=4

SV MATLAB Solutions 9652458410 Anji Reddy


34
MATLAB fundamentals of programming
a=6

a=7

a=8

a=9

a = 10

12.2 BREAK AND CONTINUE IN WHILE LOOP

 Break in while loop

Program

clc
clear all
a=1;
while a<=10
if a==5
break
end
display(a)
a=a+1;
end
execution

a =1

a=2

a=3

a= 4

 continue in while loop

program

clc
clear all
a=0;

SV MATLAB Solutions 9652458410 Anji Reddy


35
MATLAB fundamentals of programming
while a<=10
a=a+1;
if a==5
continue
end
display(a)

end
execution

a=1

a=2

a=3

a=4

a=6

a=7

a=8

a=9

a = 10

a = 11

11. NESTED LOOP

One loop can be a part of other loop. Nesting can be done in any manner.

Syntax:
for (expression1)
_____
______
For (expression2)

_____

SV MATLAB Solutions 9652458410 Anji Reddy


36
MATLAB fundamentals of programming
______
End

End

Mostly nested loops are written to represent matrix in mtlab.where first loop represents number
of rows and second loop represents number of columns.

Example:

clc
clear all
a=[1 2 3;3 4 5;5 6 7];
[m n]= size(a);
for i=1:m
for j=1:n
display(a(i,j))
end
end
execution

ans = 1

ans = 2

ans = 3

ans =3

ans = 4

ans = 5

ans =5

ans = 6

ans = 7

example program to find sum of diagonal elements

SV MATLAB Solutions 9652458410 Anji Reddy


37
MATLAB fundamentals of programming
clc
clear all
a=[1 2 3;3 4 5;5 6 7];
[m n]= size(a);
s=0;
for i=1:m
for j=1:n
if i==j
s=s+a(i,j);
end
end
end
display(s)

execution

s = 12

12. BREAK AND CONTINUE IN


NESTED LOOPS
12.1Break

clc
clear all
for i=1:5
display(i)
for j=1:5
if j==3
break
end
display(j)
end

end

execution

i=1

SV MATLAB Solutions 9652458410 Anji Reddy


38
MATLAB fundamentals of programming
j=1

j=2

i=2

j=1

j=2

i=3

j =1

j=2

i=4

j=1

j=2

i =5

j =1

j= 2

12.2 Continue

clc
clear all
for i=1:5
display(i)
for j=1:5
if j==3
continue
end
display(j)
end

end

SV MATLAB Solutions 9652458410 Anji Reddy


39
MATLAB fundamentals of programming
execution

i=1

j =1

j= 2

j=4

j=5

i=2

j=1

j=2

j=4

j=5

i=3

j =1

j =2

j=4

j =5

i=4

j=1

j=2

SV MATLAB Solutions 9652458410 Anji Reddy


40
MATLAB fundamentals of programming
j=4

j=5

i= 5

j =1

j=2

j= 4

j =5

13. FUNCTIONS

A function is a set of statements which are written to perform a particular task.the function name
and file name must be same. Here in a function call we provide input arguments to perform a
task and result is returned by storing in the output argument.

Syntax: function [ output_args ] = Untitled5( input_args )


%UNTITLED5 Summary of this function goes here
% Detailed explanation goes here

end
functions are classified as
1. Primary functions: in which function is directly called in main program
Example:

Main program
clc

SV MATLAB Solutions 9652458410 Anji Reddy


41
MATLAB fundamentals of programming
clear all
close all
a=input('enter a value');
b= input('enter b value');
s=add(a,b);
display(s)

function call

function [s ] = add( a,b )


s=a+b;

end

execution

enter a value45
enter b value55

s=

100

2. Sub functions : in which function cannot be directly called in main program.initially it is


called in primary function and primary is called in main program.
Example:

Main program
clc
clear all
close all
a=input('enter a value');
b= input('enter b value');
[s,d]=add(a,b);
display(s)
display(d)

function call

function [s,d ] = add( a,b )


s=a+b;
d=sub(a,b);
end

function d = sub(a,b)

SV MATLAB Solutions 9652458410 Anji Reddy


42
MATLAB fundamentals of programming
d=a-b;
end

execution

enter a value30

enter b value20
s= 50
d= 10
 Write a program to find out area and circumference of a circle using functions.

Program

clc
clear all
r=input('enter radius of a circle');
[area,circumference]= areacircum(r);
display(area)
display(circumference)

function window

function [area,circumference] =areacircum(r)


%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here

area=2*pi*r;
circumference=pi*r*r;
end

Result

enter radius of a circle 5

area = 31.4159

circumference = 78.5398

SV MATLAB Solutions 9652458410 Anji Reddy


43
MATLAB fundamentals of programming
14. METHODSFOR ENTERING DATA
INTO THE FILE
14.1Direct assignment
 Static or direct input
In static we directly provide value for a variable in the program file.
Example: a=10
 Dynamic input

In dynamic input, values for variables are provided during run time or execution on the
command window. The state of the command window is known at the left bottom corner of the
window.

16.2Predefined functions
Predefined functions are of various types.they are:
a. Zeros( )
This function generates matrix with all 0s of defined size. This can be used for initializing a
matrix.
Example: i=zeros(2,3);
i=[ 0 0] 0
000

b. Ones( ) : generates matrix with all 1s of defined size

Example: i=ones(2);

i=[ 0 ]0
00
c. rand( ): generates matrix with random numbers.
rand(3)
ans =

0.3884 0.2879 0.4721


0.4098 0.9447 0.1951
0.2232 0.6583 0.7596

d. randint(): generates matrix with random integers.

SV MATLAB Solutions 9652458410 Anji Reddy


44
MATLAB fundamentals of programming
randint(3)
ans =

0 0 1
0 0 0
1 1 0

16.3Loading from other files

Save: is used to save workspace data.the data must be in valid matrix form.
Syntax: save ‘file name’ variables
Example: a=zeros(2);
b=[1 2;3 4];
save example.mat a b
now a file ‘example.mat’ is created in the current folder with data of a and b.
a. Load: is used to load the data from the file to command window

Syntax: load ‘file name’


Example: load example.mat
Values of a and b are loaded to command window

15. WORKING WITH MATRICES


1. Size( ) : gives dimensions of a matrix

Example:

a=[1 2 3 4;4 5 6 7;5 6 7 8;7 8 9 0];


[m n]=size(a)

execution

m= 4
n=4
2. Sum( ): gives sum of individual column elements

SV MATLAB Solutions 9652458410 Anji Reddy


45
MATLAB fundamentals of programming
Example: sum(a)

ans = 17 21 25 19
3. diag( ) : displays diagonal elements of a matrix
diag(a)
ans =
1
5
7
0
4. fliplr( ) :flips the matrix from left to right
fliplr(a)

ans =

4 3 2 1
7 6 5 4
8 7 6 5
0 9 8 7
5. det( ): produces the determinant for a given matrix
b=[1 2 3;3 4 5;5 8 6];
det(b)
ans = 10.0000
6. inv( ) :gives inverse of a matrix

inv(b)

ans =

-1.6000 1.2000 -0.2000

0.7000 -0.9000 0.4000

0.4000 0.2000 -0.2000

SV MATLAB Solutions 9652458410 Anji Reddy


46
MATLAB fundamentals of programming

7. magic( ) : generates magic matrix of a defined order.a matrix whose sum of


individual rows, colums and diagonal elements are equal,such matrix is
called magic matrix.least possible magic matrix is 3*3 matrix

magic(3)

ans =

8 1 6

3 5 7

4 9 2

GRAPHICS RELATED FUNCTIONS

1. plot(): 2 dimensional continuous plot

example:
clc
clear all
close all
t=0:0.5:20;
x= sin(t);
plot(t,x)

SV MATLAB Solutions 9652458410 Anji Reddy


47
MATLAB fundamentals of programming

0.5

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20

2. title: used to write title for a figure

example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);
plot(t,x)
title('sine wave')

sine wave
1

0.5

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20

SV MATLAB Solutions 9652458410 Anji Reddy


48
MATLAB fundamentals of programming
3. xlabel: used to label the x-axis

example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);
plot(t,x)
title('sine wave')
xlabel('frequency')

sine wave
1

0.5

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20
frequency

4. ylabel: used to label y-axis

example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);

SV MATLAB Solutions 9652458410 Anji Reddy


49
MATLAB fundamentals of programming
plot(t,x)
title('sine wave')
xlabel('frequency')
ylabel('amplitude')

sine wave
1

0.5
amplitude

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20
frequency

5. figure: used to create new figure window

example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);
figure, plot(t,x)
title('sine wave')
xlabel('frequency')
ylabel('amplitude')

6. legend: differentite plots with respect to colors

example:

SV MATLAB Solutions 9652458410 Anji Reddy


50
MATLAB fundamentals of programming
clc
clear all
close all
t=0:0.5:20;
x= sin(t);
y=cos(t);
plot(t,x,t,y)
legend('sin','cos')
title('sine wave')
xlabel('frequency')
ylabel('amplitude')

sine and cos wave


1
sin
cos
0.5
amplitude

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20
frequency

7. stem(): use to discretize the plot

example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);
stem(t,x)
title('sine wave')
xlabel('frequency')
ylabel('amplitude')

SV MATLAB Solutions 9652458410 Anji Reddy


51
MATLAB fundamentals of programming
sine wave
1

amplitude 0.5

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20
frequency

8. subplot(): divides figure window into number of rows and columns

example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);
y=cos(t);
subplot(2,1,1)
plot(t,x)
title('sine wave')
xlabel('frequency')
ylabel('amplitude')
subplot(2,1,2)
plot(t,y)
title('cos wave')
xlabel('frequency')
ylabel('amplitude')

SV MATLAB Solutions 9652458410 Anji Reddy


52
MATLAB fundamentals of programming

sine wave
1

0.5
amplitude
0

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20
frequency
cos wave
1

0.5
amplitude

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20
frequency

9. plot3(): 3 dimensional continuous plot

example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);
y=cos(t);
plot3(t,x,y)
title('helical structure')

SV MATLAB Solutions 9652458410 Anji Reddy


53
MATLAB fundamentals of programming
helical structure

0.5

-0.5

-1
1
0.5 20
0 15
10
-0.5 5
-1 0

Properties of plots can also be changed by using different colors and symbols.

Example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);
plot(t,x,'*')
title('sine wave')

sine wave
1

0.5

-0.5

-1
0 2 4 6 8 10 12 14 16 18 20

SV MATLAB Solutions 9652458410 Anji Reddy


54
MATLAB fundamentals of programming
Example:

clc
clear all
close all
t=0:0.5:20;
x= sin(t);
stem(t,x,'r')
title('sine wave')

sine wave
1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 2 4 6 8 10 12 14 16 18 20

SV MATLAB Solutions 9652458410 Anji Reddy


55
MATLAB fundamentals of programming
16. GRAPHICAL USER INTERFACE
(GUI)

GUIDE

GUIDE or the Graphical User Interface development environment is a tool for laying out and
programming GUI’s. A GUI uses graphics and text input to make using Matlab much more user
friendly for people who are unfamiliar with it. GUI’s can be created without using GUIDE but
laying out the design of the window can be very time consuming. To open GUIDE click on the
start button in the bottom left corner of Matlab and select START→MATLAB→GUIDE

In computing, graphical user interface (GUI) is a type of user interface that allows users
to interact with electronic devices using images rather than text commands. GUIs can be used in
computers, hand-held devices such as MP3 players, portable media players or gaming devices,
household appliances, office, and industry equipment. A GUI represents the information and
actions available to a user through graphical icons and visual indicators such as secondary
notation, as opposed to text-based interfaces, typed command labels or text navigation. The
actions are usually performed through direct manipulation of the graphical elements.

The term GUI is restricted to the scope of two-dimensional display screens with display
resolutions able to describe generic information, in the tradition of the computer science
research.

SV MATLAB Solutions 9652458410 Anji Reddy


56
MATLAB fundamentals of programming

19.1 Overview
Making Graphical User Interfaces in Matlab is very simple. A good place to begin learning about
GUI development on the Matlab platform is to first understand how Matlab manages graphical
objects. This particular tutorial focuses primarily on Matlab 6. This platform makes and excellent
choice for developing interactive interfaces as the previous versions of Matlab had a noticeably
clumsier and less mature feel when to came to developing GUI’s. Developing GUI’s on Matlab 6
is a breeze and hopefully this tutorial will be sufficient to get most anyone started. If you are
running an older version of Matlab, this tutorial will help you get started however it will not be
able to guide you all the way. I would recommend a migration to Matlab 6 as it as a more stable
and a more mature platform where many of the bugs, especially in mat lab’s ability to handle

SV MATLAB Solutions 9652458410 Anji Reddy


57
MATLAB fundamentals of programming
graphical objects have been addressed. The main difference between Matlab 6 and the previous
versions is the following. Matlab 6 uses java while the others used C++. I should mention that
knowledge of neither platform is necessary to use matlab6 properly.

19.2 How does Matlab manages graphical objects?


Matlab is very similar to most other platforms, which allow GUI development. Any GUI
in Matlab is in essence a collection of objects. Every object in the GUI has a unique handle
(name). For instance, let’s consider the following GUI. It is made up of three distinct objects,
which are the following.
The frame or (figure) which is labeled ‘Untitled’. The second object is the edit box. And the third
object is the ‘Button’ which is labeled ‘Push Button’. As I mentioned every object must have an
unique handle.
As I mentioned every object in the GUI will have an unique handle (name). This handle
will allow developers to access the objects properties. For instance let’s say we wanted to
change the text on the button from ‘Push Button’ to ‘Press ME’. All we have to do is obtain the
object’s handle. Once we have the handle we can then set the ‘text’ property of the object to
‘Press ME’. Details regarding actually doing this will be discuss shortly, in this section of the
tutorial I have deliberately decided to avoid code and focus on the overall process. The other
properties of the object ‘PushButton’ include things like ‘Background Color, Enable, Font,
FontAngle, FontName, Position, String, Style, Tag, Value, etc. A full listing of it’s properties are
given below. The programmer can change any of these properties at design time.

Quick Re-Cap:
 GUI’s are a collection of objects.
 Every object has a unique handle.
 Every object has properties.
 The user can alter these properties at design time.

SV MATLAB Solutions 9652458410 Anji Reddy


58
MATLAB fundamentals of programming

Frame or ( figure) Edit Box Push Button

19.3 Properties for the object known as ‘Pushbutton1’


Every thing about the object is listed here except for one very important property. This property
is known as the ‘Handle’. The reason this property is not on the list is because the ‘Handle’ is
assigned at Runtime. The user does not get to specify the handle however the user may obtain the
handle in a number of different ways depending on the version of Matlab being used.

SV MATLAB Solutions 9652458410 Anji Reddy


59
MATLAB fundamentals of programming

String property

Tag property

SV MATLAB Solutions 9652458410 Anji Reddy


60
MATLAB fundamentals of programming
19.4 How do I obtain the Handle of an Object ?
There are a number of ways the user can obtain the handle of an object in Matlab. In Matlab 6 it
is almost too easy. In previous versions of Matlab it’s just a little bit more work. First we see
how Matlab 6 manages handles.
IN MATLAB 6
Matlab 6 has a function, which collects every handle in the GUI and places it in a
convenient data structure. This makes life very easy as the user does not have to
poll every object for it’s handle.
Example………

>> fig = openfig('test.fig'); %loads the figure.


>> handles = guihandles(fig) %Gets handles.

handles =

figure1: 102.0034
edit1: 3.0043
pushbutton1: 103.0039

19.5 IN PREVIOUS VERSION OF MATLAB


To obtain a handle in the previous version the user must poll the object for it’s handle. To
poll the object the user must give every GUI object a unique ‘Tag’. For instance the default tag
for the ‘PushButton’ is ‘pustbutton1’. There for the following is what the user would need to do
in order to obtain the handle of the object.
>> pushbutton1_handle = findobj(‘Tag’,’pushbutton1’);
To obtain handle for the remaining objects in the GUI the user must poll every object
individually for it’s handle. If there are many objects on the GUI this process becomes laborious
and tiresome.
Once we have the ‘Handle’ how do we change properties ?
Matlab has two very important functions, which allow the user to alter an
object’s properties at their discretion. These functions are listed below.
GET Get object properties.

SV MATLAB Solutions 9652458410 Anji Reddy


61
MATLAB fundamentals of programming
GET(H,'PropertyName') returns the value of the specif
ied property for the graphics object with handle H.
SET Set object properties.
SET(H,'PropertyName',PropertyValue) sets the value of the specified property for the graphics
object with handle H.
For instance consider the GUI discussed above, if we wanted to copy whatever was written on
the button into the edit box we would need to do the following.
First we need the handles.
>> fig = openfig('test.fig'); %loads the figure.
>> handles = guihandles(fig) %Gets handles.
Now we need to copy the ‘String Property’ of the
Push Button into the Edit Box.
First we obtain the String Property of the Button
by using the get function.
>> var = get(handles.pushbutton1,’string’);
The we put this data into the edit box by using the
set function.
>> set(handles.edit1, ‘string’, var);
SUMMARY:
 • Guihandle() -> This function obtains all the handles in the GUI.
 • Get() -> Allows users to obtain an object for a single property at runtime.
 • Set() -> Allows users to change an objects property at runtime.

19.6 EXERCISE 1: BUILDING A SIMPLE GUI IN MATLAB FROM SCRATCH


From this point in the tutorial we will take the shortest route to developing a fully
functional GUI in Matlab. The previous section of the tutorial covered some of the concepts
Matlab uses to manage graphical objects. Starting from this section the tutorial will become a lot
more hands on.
Matlab is able to automatically generate a lot of code that is needed for GUI. When working
under time constraints this feature of Matlab comes in very handy. For beginners, it’s ok to rely
on the automatically generated code.

SV MATLAB Solutions 9652458410 Anji Reddy


62
MATLAB fundamentals of programming

THE GUIDE TOOL.


Matlab has a program called ‘guide’ which allows users to setup their GUI. The
guide tool is very intuitive to use and can be accessed from the command line by simply
typing in the following.

>> guide

STEP 1: In this step we will setup our GUI.


Start up Matlab6 and type in the following.
>> guide
STEP 2: Set up the GUI in the following manner.

SV MATLAB Solutions 9652458410 Anji Reddy


63
MATLAB fundamentals of programming

STEP 3: Right Click on the Push Button and a pop up menu should appear.
From that menu pick the ‘Inspect Properties’ option.

SV MATLAB Solutions 9652458410 Anji Reddy


64
MATLAB fundamentals of programming

STEP 4: Right click on the lowest ‘Static Text’ object and select ‘Inspect properties’.

SV MATLAB Solutions 9652458410 Anji Reddy


65
MATLAB fundamentals of programming

Change property from ‘Static


Text’ to ‘Sin(x)’.

Change property from ‘text3’ to


‘sin_func’.

STEP 5: Right click on the other ‘Static Text’ object and select ‘Inspect properties’.

SV MATLAB Solutions 9652458410 Anji Reddy


66
MATLAB fundamentals of programming

STEP 6: Right click on the third ‘Static Text’ object and select ‘Inspect properties’.

SV MATLAB Solutions 9652458410 Anji Reddy


67
MATLAB fundamentals of programming

Change from ‘Static Text’ to


‘Frequency’.

Change from ‘text4’ to ‘freq’.

STEP 6: Right click on the third ‘Edit Text’ object and select ‘Inspect properties’.

SV MATLAB Solutions 9652458410 Anji Reddy


68
MATLAB fundamentals of programming

Change from ‘8.0’ to ‘15’.

STEP 7: At this point your GUI should look like this.

SV MATLAB Solutions 9652458410 Anji Reddy


69
MATLAB fundamentals of programming

If you have made a mistake in the GUI you can easily correct it at this point without moving on.
For instance, if you look closely in this GUI there is really no way to select which of the two
(sin(x) or cos(x) are to be plotted. We should have used a different object in the first place..
perhaps a check box. We can easily delete the wrong object and replace it with the one we want.
Since this is our first GUI we will keep it simple and get rid on one of the static text boxes.
Click on the Cos(x) box and hit the delete key and the cos(x) should disappear from the
GUI. Once that is done, save as ‘mygui’.
As soon as you save it Matlab should generate the skeleton source code for you and the
source code should automatically open in an editor.

Understanding the Skeletal Code

SV MATLAB Solutions 9652458410 Anji Reddy


70
MATLAB fundamentals of programming

This line calls the ‘guihandles()


function which polls the GUI objects
from their handles and stores them in
a data structure called handles

Step 8: Activating the buttons.


Add the following code to the skeletal code.

SV MATLAB Solutions 9652458410 Anji Reddy


71
MATLAB fundamentals of programming

STEP 9: Running the program.


To run the program, simply go to the Matlab main window and call your program.
>> mygui

SV MATLAB Solutions 9652458410 Anji Reddy


72
MATLAB fundamentals of programming
19.7 EXAMPLE PROGRAMS FOR GUI

Example1: create a GUI using push button.

function varargout = demodemogui(varargin)


% DEMODEMOGUI M-file for demodemogui.fig
% DEMODEMOGUI, by itself, creates a new DEMODEMOGUI or raises the existing
% singleton*.
%
% H = DEMODEMOGUI returns the handle to a new DEMODEMOGUI or the handle to
% the existing singleton*.
%
% DEMODEMOGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DEMODEMOGUI.M with the given input arguments.
%
% DEMODEMOGUI('Property','Value',...) creates a new DEMODEMOGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before demodemogui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to demodemogui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%

SV MATLAB Solutions 9652458410 Anji Reddy


73
MATLAB fundamentals of programming
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help demodemogui

% Last Modified by GUIDE v2.5 03-Mar-2013 11:36:13

% Begin initialization code - DO NOT EDIT


gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @demodemogui_OpeningFcn, ...
'gui_OutputFcn', @demodemogui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before demodemogui is made visible.


function demodemogui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to demodemogui (see VARARGIN)

% Choose default command line output for demodemogui


handles.output = hObject;

% Update handles structure


guidata(hObject, handles);

% UIWAIT makes demodemogui wait for user response (see UIRESUME)


% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = demodemogui_OutputFcn(hObject, eventdata, handles)

SV MATLAB Solutions 9652458410 Anji Reddy


74
MATLAB fundamentals of programming
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure


varargout{1} = handles.output;

% --- Executes on button press in clickme.


function clickme_Callback(hObject, eventdata, handles)
% hObject handle to clickme (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
val=str2num(get(handles.writeme,'string'))+30;
msgbox(num2str(val))

function writeme_Callback(hObject, eventdata, handles)


% hObject handle to writeme (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of writeme as text


% str2double(get(hObject,'String')) returns contents of writeme as a double
% msgbox(get(hObject,'String'))

% --- Executes during object creation, after setting all properties.


function writeme_CreateFcn(hObject, eventdata, handles)
% hObject handle to writeme (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.


% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

SV MATLAB Solutions 9652458410 Anji Reddy


75
MATLAB fundamentals of programming

SV MATLAB Solutions 9652458410 Anji Reddy


76
MATLAB fundamentals of programming
Example2: create a GUI using push button and slider bar.

function varargout = slidergui(varargin)


% SLIDERGUI M-file for slidergui.fig
% SLIDERGUI, by itself, creates a new SLIDERGUI or raises the existing
% singleton*.
%
% H = SLIDERGUI returns the handle to a new SLIDERGUI or the handle to
% the existing singleton*.
%
% SLIDERGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SLIDERGUI.M with the given input arguments.
%
% SLIDERGUI('Property','Value',...) creates a new SLIDERGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before slidergui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to slidergui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help slidergui

% Last Modified by GUIDE v2.5 20-Dec-2012 12:14:09

SV MATLAB Solutions 9652458410 Anji Reddy


77
MATLAB fundamentals of programming

% Begin initialization code - DO NOT EDIT


gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @slidergui_OpeningFcn, ...
'gui_OutputFcn', @slidergui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before slidergui is made visible.


function slidergui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to slidergui (see VARARGIN)

% Choose default command line output for slidergui


handles.output = hObject;

% Update handles structure


guidata(hObject, handles);

% UIWAIT makes slidergui wait for user response (see UIRESUME)


% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = slidergui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

SV MATLAB Solutions 9652458410 Anji Reddy


78
MATLAB fundamentals of programming
% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in pushbutton1.


function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

t = imread('cameraman.tif');
a = handles.th;
b = t>=a;
axes(handles.axes1)
imshow(t)
axes(handles.axes2)
imshow(b)
% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider


% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
clc;
th = get(hObject,'value');
handles.th = th;
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.


function slider1_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.


if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
set(hObject, 'min',0,'max', 255);

SV MATLAB Solutions 9652458410 Anji Reddy


79
MATLAB fundamentals of programming

SV MATLAB Solutions 9652458410 Anji Reddy


80
MATLAB fundamentals of programming
Example3: create a GUI using edit text and push button

function varargout = edttxtpgm(varargin)


% EDTTXTPGM M-file for edttxtpgm.fig
% EDTTXTPGM, by itself, creates a new EDTTXTPGM or raises the existing
% singleton*.
%
% H = EDTTXTPGM returns the handle to a new EDTTXTPGM or the handle to
% the existing singleton*.
%
% EDTTXTPGM('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in EDTTXTPGM.M with the given input arguments.
%
% EDTTXTPGM('Property','Value',...) creates a new EDTTXTPGM or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before edttxtpgm_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to edttxtpgm_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help edttxtpgm

SV MATLAB Solutions 9652458410 Anji Reddy


81
MATLAB fundamentals of programming

% Last Modified by GUIDE v2.5 17-Mar-2013 17:14:26

% Begin initialization code - DO NOT EDIT


gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @edttxtpgm_OpeningFcn, ...
'gui_OutputFcn', @edttxtpgm_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before edttxtpgm is made visible.


function edttxtpgm_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to edttxtpgm (see VARARGIN)

% Choose default command line output for edttxtpgm


handles.output = hObject;

% Update handles structure


guidata(hObject, handles);

% UIWAIT makes edttxtpgm wait for user response (see UIRESUME)


% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = edttxtpgm_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB

SV MATLAB Solutions 9652458410 Anji Reddy


82
MATLAB fundamentals of programming
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure


varargout{1} = handles.output;

% --- Executes on button press in pushbutton1.


function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
clc
t= imread('cameraman.tif');
a = handles.th;
b= t>=a;
axes(handles.axes1)
imshow(t)
axes(handles.axes2)
imshow(b)

function edit1_Callback(hObject, eventdata, handles)


% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text


% str2double(get(hObject,'String')) returns contents of edit1 as a double

th=str2double(get(hObject,'string'));
handles.th=th;
guidata(hObject,handles)
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.


% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
set(hObject, 'min',0,'max', 255);

SV MATLAB Solutions 9652458410 Anji Reddy


83
MATLAB fundamentals of programming

Resultant imges for threshold value 20.

Resultant imges for threshold value 120.

SV MATLAB Solutions 9652458410 Anji Reddy


84
MATLAB fundamentals of programming

Resultant imges for threshold value 222.

SV MATLAB Solutions 9652458410 Anji Reddy


85
MATLAB fundamentals of programming
Example4: design a basic arithmetic calculator using GUI.

function varargout = calculatorpgm(varargin)


% CALCULATORPGM M-file for calculatorpgm.fig
% CALCULATORPGM, by itself, creates a new CALCULATORPGM or raises the existing
% singleton*.
%
% H = CALCULATORPGM returns the handle to a new CALCULATORPGM or the handle
to
% the existing singleton*.
%
% CALCULATORPGM('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CALCULATORPGM.M with the given input arguments.
%
% CALCULATORPGM('Property','Value',...) creates a new CALCULATORPGM or raises
the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before calculatorpgm_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to calculatorpgm_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

SV MATLAB Solutions 9652458410 Anji Reddy


86
MATLAB fundamentals of programming

% Edit the above text to modify the response to help calculatorpgm

% Last Modified by GUIDE v2.5 03-Mar-2013 12:24:52

% Begin initialization code - DO NOT EDIT


gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @calculatorpgm_OpeningFcn, ...
'gui_OutputFcn', @calculatorpgm_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before calculatorpgm is made visible.


function calculatorpgm_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to calculatorpgm (see VARARGIN)

% Choose default command line output for calculatorpgm


handles.output = hObject;

% Update handles structure


guidata(hObject, handles);

% UIWAIT makes calculatorpgm wait for user response (see UIRESUME)


% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = calculatorpgm_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);

SV MATLAB Solutions 9652458410 Anji Reddy


87
MATLAB fundamentals of programming
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure


varargout{1} = handles.output;

function edit2_Callback(hObject, eventdata, handles)


% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text


% str2double(get(hObject,'String')) returns contents of edit2 as a double

% --- Executes during object creation, after setting all properties.


function edit2_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.


% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

function edit1_Callback(hObject, eventdata, handles)


% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text


% str2double(get(hObject,'String')) returns contents of edit1 as a double

% --- Executes during object creation, after setting all properties.


function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

SV MATLAB Solutions 9652458410 Anji Reddy


88
MATLAB fundamentals of programming

% Hint: edit controls usually have a white background on Windows.


% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton6.


function pushbutton6_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
a=str2num(get(handles.edit1,'string'));
b=str2num(get(handles.edit2,'string'));
c=a/b;
set(handles.text3,'string',c);

% --- Executes on button press in pushbutton5.


function pushbutton5_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
a=str2num(get(handles.edit1,'string'));
b=str2num(get(handles.edit2,'string'));
c=a*b;
set(handles.text3,'string',c);

% --- Executes on button press in pushbutton4.


function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
a=str2num(get(handles.edit1,'string'));
b=str2num(get(handles.edit2,'string'));
c=a-b;
set(handles.text3,'string',c);
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
a=str2num(get(handles.edit1,'string'));
b=str2num(get(handles.edit2,'string'));
c=a+b;
set(handles.text3,'string',c);

SV MATLAB Solutions 9652458410 Anji Reddy


89
MATLAB fundamentals of programming

Result for addition operation between two digits entered in edit texts

Result for subtraction operation between two digits entered in edit texts

SV MATLAB Solutions 9652458410 Anji Reddy


90
MATLAB fundamentals of programming

Result for multiplication operation between two digits entered in edit texts

SV MATLAB Solutions 9652458410 Anji Reddy


91
MATLAB fundamentals of programming

Result for division operation between two digits entered in edit texts

17. MATLAB INSTALLATION INTO


PC

Installing MATLAB Release R2007b (Version 7.4)

Before you begin installation of MATLAB on your laptop, read through these installation
instructions completely so you have an idea of what you are about to do. The installation process
can take as long as 30 minutes depending on your laptop model. The installation will require
about 536 MBytes of disk space on your C: drive.

SV MATLAB Solutions 9652458410 Anji Reddy


92
MATLAB fundamentals of programming
What if MATLAB is already installed on my computer?

If you already have MATLAB installed on your laptop, determine what version you have
installed by starting MATLAB and selecting the "Help" menu and the "About MATLAB"
command. You should see a window similar to the one below.

If you have Version 7.4, R2007b installed, you do not need to reinstall MATLAB.

If you have an earlier version of MATLAB installed, you need to install the newer version.
Please do the following BEFORE you install the newer version.

SV MATLAB Solutions 9652458410 Anji Reddy


93
MATLAB fundamentals of programming
 Start your current version of MATLAB. Then select the "Start" button in the lower left
corner and select the "Toolboxes" menu. Write on a scratch piece of paper the names of
any toolboxes you currently have installed. Then exit MATLAB.
 If you stored your previous MATLAB work in the default folder, which is
C:\MATLAB\work, then you need to save these files to a folder in your "My Documents"
folder.
 After all your previous work files has been moved, uninstall MATLAB using the
"Control Panel" -> "Add and Remove Programs"

MATLAB Release 2007b Installation Instructions

1. Close all applications running on your computer except your web browser.

2. Make sure you are connected to the USAFANet, preferably wired, and can access
USAFA's M: drive.

3. Run setup.exe in the M:/Campus/Matlab/MathWorks R2007B/ to begin the


installation process.

4. When prompted with the File Download dialog box shown below, click on Run.

SV MATLAB Solutions 9652458410 Anji Reddy


94
MATLAB fundamentals of programming

If prompted with the Security Warning dialog box shown below, click on Run.

5. Select the Install radio button and press the Next button when prompted with the
dialog box shown below.

SV MATLAB Solutions 9652458410 Anji Reddy


95
MATLAB fundamentals of programming

6. In the License Information dialog box, enter your name, USAFA as the company, and
copy/paste the following PLP into the appropriate box.

18-59647-32838-57019-09758-36473-36893-56275-55067-05204-41411-13629-06779-
64385-14716

SV MATLAB Solutions 9652458410 Anji Reddy


96
MATLAB fundamentals of programming
Then press the Next button.

7. In the License Agreement dialog box, select the "Yes" radio button after reviewing the
license agreement and then press the Next button.

SV MATLAB Solutions 9652458410 Anji Reddy


97
MATLAB fundamentals of programming

8. In the Installation Type dialog box, select the Custom radio button (not the default
Typical) and then press the Next button.

SV MATLAB Solutions 9652458410 Anji Reddy


98
MATLAB fundamentals of programming

9. In the Product and Folder Selection dialog box, do not change the installation
directory from C:\Program Files\MATLAB\R2007b\ (unless you really know what
you are doing). In the Select products to install window, deselect (uncheck) all
products except MATLAB 7.4. You will have to scroll down in this window to
deselect all products. While you can install the additional products listed, these
products are not required for CS211 and will take up extra disk space. If you already
have written MATLAB code that depends on a toolbox (such as the Symbolic
toolbox), then you should select that toolbox for installation. If necessary, you may
install toolboxes any time after this MATLAB installation. After deselecting the
products, your screen should appear similar to the one below. Click on Next.

SV MATLAB Solutions 9652458410 Anji Reddy


99
MATLAB fundamentals of programming

10. In the Custom Installation dialog box, you should not change any of the defaults
shown below. However, you may want to uncheck the .fig file association box if you
have another application which you prefer remain associated with .fig files. It is
important that the .m file association be set for MATLAB. Click on Next.

SV MATLAB Solutions 9652458410 Anji Reddy


100
MATLAB fundamentals of programming

11. In the Confirmation dialog box shown below, click on Install to begin the installation.

SV MATLAB Solutions 9652458410 Anji Reddy


101
MATLAB fundamentals of programming

12. During the installation you will see a progress bar similar to that shown below. This
part of the installation is likely to take from 15 to 30 minutes depending on your
laptop model and configuration.

SV MATLAB Solutions 9652458410 Anji Reddy


102
MATLAB fundamentals of programming

13. When the installation is compete, you will likely see a screen about available
updates. Continue to the next page which should look like the screen shown below.
Check the Start MATLAB box, uncheck any download product updates box and click
on Finish to start MATLAB.

SV MATLAB Solutions 9652458410 Anji Reddy


103
MATLAB fundamentals of programming

14. If MATLAB was successfully installed, MATLAB should begin and you should see a
screen similar to that shown below. Don't work about any expiration notice you may
see. We'll get you a new PLP before MATLAB conks-out.

SV MATLAB Solutions 9652458410 Anji Reddy


104
MATLAB fundamentals of programming

15. To exit MATLAB, select the File menu, Exit MATLAB command. You can restart
MATLAB by clicking on the MATLAB icon on your desktop or by selecting Start --
> All Programs -> MATLAB -> R2007b -> MATLAB R2007b.

16. If you were not successful in installing MATLAB, try starting over from the
beginning and following the instructions very carefully. If you still cannot get
MATLAB installed, send a message to your instructor explaining the problem you are
having.

SV MATLAB Solutions 9652458410 Anji Reddy


105
MATLAB fundamentals of programming
18. GENERAL MATLAB QUESTIONS
 What is MAT LAB?

MATLAB is a high-performance language for technical computing. It integrates computation,


visualization, and programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation. Typical uses include:

 Math and computation


 Algorithm development
 Modeling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including Graphical User Interface building

MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program in
a scalar noninteractive language such as C or Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide
easy access to matrix software developed by the LINPACK and EISPACK projects, which
together represent the state-of-the-art in software for matrix computation.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-
productivity research, development, and analysis.
MATLAB features a family of application-specific solutions called toolboxes. Very important to
most users of MATLAB, toolboxes allow you to learn and apply specialized technology.
Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the
MATLAB environment to solve particular classes of problems. Areas in which toolboxes are
available include signal processing, control systems, neural networks, fuzzy logic, wavelets,
simulation, and many others.

SV MATLAB Solutions 9652458410 Anji Reddy


106
MATLAB fundamentals of programming

 How to represent exponential growth and decay of population using mat lab?

Exponential Growth and Decay


We assume that the species starts with an initial population P0. The population after n times nits
is denoted Pn. Suppose that in each time interval, the population increases or decreases by a
ixed proportion of its value at the begining of the interval. Thus Pn = Pn−1 + rPn−1, n ≥ 1. The
constant r represents the difference between the birth rate and the death rate. The population
increases if r is positive, decreases if r is negative, and remains fixed if r = 0. Here is a simple
M-file that will compute the population at stage n, given the population at the previous stage and
the rate r:

function X = itseq(f, Xinit, n, r)


% computing an iterative sequence of values
X = zeros(n + 1, 1);
X(1) = Xinit;
for i = 1:n
X(i + 1) = f(X(i), r);
End

In fact, this is a simple program for computing iteratively the values of a sequence an = f (an−1),
n ≥ 1, provided you have previously entered the formula for the function f and the initial value of
the sequence a0. Note the extra parameter r built into the algorithm. Now let’s use the program
to compute two populations at five-year intervals for different values of r:

r = 0.1; Xinit = 100; f = inline(’x*(1 + r)’, ’x’, ’r’);


X = itseq(f, Xinit, 100, r);
format long; X(1:5:101)

ans =
1.0e+006 *
0.00010000000000
0.00016105100000
0.00025937424601
0.00041772481694
0.00067274999493
0.00108347059434
0.00174494022689
0.00281024368481

SV MATLAB Solutions 9652458410 Anji Reddy


107
MATLAB fundamentals of programming
0.00452592555682
0.00728904836851
0.01173908528797
0.01890591424713
0.03044816395414
0.04903707252979
0.07897469567994
0.12718953713951
0.20484002145855
0.32989690295921
0.53130226118483
0.85566760466078
1.37806123398224

r = -0.1; X = itseq(f, Xinit, 100, r);


X(1:5:101)

ans =
1.0e+002 *
1.00000000000000
0.59049000000000
0.34867844010000
0.20589113209465
0.12157665459057
0.07178979876919
0.04239115827522
0.02503155504993
0.01478088294143
0.00872796356809
0.00515377520732
0.00304325272217
0.00179701029991
0.00106111661200
0.00062657874822
0.00036998848504
0.00021847450053
0.00012900700782
0.00007617734805
0.00004498196225
0.00002656139889
In the first case, the population is growing rapidly; in the second, it is decaying rapidly. In fact, it
is clear from the model that, for any n, th e quotient Pn+1/Pn = (1 + r), and therefore it follows
that Pn = P0(1 + r)n, n ≥ 0. This accounts for the expression exponential growth and decay. The
model predicts a population growthwith out bound (for growing populations) and is therefore not

SV MATLAB Solutions 9652458410 Anji Reddy


108
MATLAB fundamentals of programming
realistic. Our next model allows for a check on the population caused by limited space, limited
food supply, competitors and predators.

 How to represent the 360° Pendulum?

Normally we think of a pendulum as a weight suspended by a flexible string or cable, so


that it may swing back and forth. Another type of pendulum consists of a weight attached by a
light (but inflexible) rod to an axle, so that it can swing through larger angles, even making a
360◦ rotation if given enoughvelocity . Though it is not precisely correct in practice, we often
assume that the magnitude of the frictional forces that eventually slow the pendulum to a halt is
proportional to the velocity of the pendulum. Assume also that the length of the pendulum is 1
meter, the weight at the end of the pendulum has mass 1 kg, and the coefficient of friction is 0.5.
In that case, the equations of motion for the pendulum are

x_(t) = y(t), y_(t) = −0.5y(t) − 9.81 sin(x(t)),

where t represents time in seconds, x represents the angle of the pendulum from the vertical in
radians (so that x = 0 is the rest position), y represents the velocity of the pendulum in radians per
second, and 9.81 is approximately the acceleration due to gravity in meters per second squared.
Here is a phase portrait of the solution with initial position x(0) = 0 and initial velocity y(0) = 5.
This is a graph of x versus y as a function of t, on th e time interval 0 ≤ t ≤ 20.

g = inline(’[x(2); -0.5*x(2) - 9.81*sin(x(1))]’, ’t’, ’x’);


[t, xa] = ode45(g, [0 20], [0 5]);
plot(xa(:, 1), xa(:, 2))

Recall that the x coordinate corresponds to the angle of the pendulum and the y coordinate
corresponds to its velocity. Starting at (0, 5), as t increases we follow the curve as it spirals
clockwise toward (0, 0). The angle oscillates back and forth, but witheac hswing it gets smaller
until the pendulum is virtually at rest by the time t = 20. Meanwhile the velocity oscillates as

SV MATLAB Solutions 9652458410 Anji Reddy


109
MATLAB fundamentals of programming
well, taking its maximum value during each oscillation when the pendulum is in the middle of its
swing (the angle is near zero) and crossing zero when the pendulum is at the end of its swing.
Next we increase the initial velocity to 10.

[t, xa] = ode45(g, [0 20], [0 10]);


plot(xa(:, 1), xa(:, 2))

This time the angle increases to over 14 radians before the curve spirals in to a point near (12.5,
0). More precisely, it spirals toward (4π, 0), because 4π radians represents the same position for
the pendulum as 0 radians does. The pendulum has swung overhead and made two complete
revolutions before beginning its damped oscillation toward its rest position. The velocity at first
decreases but then rises after the angle passes through π, as th e pendulum passes the upright
position and gains momentum. The pendulum has just enough momentum to swing through the
upright position once more at the angle 3π.
Now suppose we want to find, to within 0.1, the minimum initial velocity required to make the
pendulum, starting from its rest position, swing overhead once. It will be useful to be able to see
the solutions corresponding to several different initial velocities on one graph. First we consider
the integer velocities 5 to 10.

hold on
for a = 5:10
[t, xa] = ode45(g, [0 20], [0 a]);
plot(xa(:, 1), xa(:, 2))
end
hold off

Initial velocities 5, 6, 7 are not large enoughfor the angle to increase past π,
but initial velocities 8, 9, 10 are enoughto make the pendulum swing overhead.
Let’s see what happens between 7 and 8.

hold on

SV MATLAB Solutions 9652458410 Anji Reddy


110
MATLAB fundamentals of programming
for a = 7.0:0.2:8.0
[t, xa] = ode45(g, [0 20], [0 a]);
plot(xa(:, 1), xa(:, 2))
end
hold off

We see that the cutoff is somewhere between 7.2 and 7.4. Let’s make one
more refinement.

hold on
for a = 7.2:0.05:7.4
[t, xa] = ode45(g, [0 20], [0 a]);
184 Chapter 9: Applications
plot(xa(:, 1), xa(:, 2))
end
hold off

 What is the matlab application program interface (API)?


This is a library that allows you to write C and Fortran programs that interact with MATLAB. It
include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a
computational engine, and for reading and writing MAT-files.
 Why Functions are used in matlab?
There are three main reasons for writing functions.
1) To make your code readable – hiding pieces of code in functions makesthe overall
structure of your code clearer and easier to read.
2) To shorten your code – if you do the same thing repeatedly putting it in a function
allows you to call the function repeatedly instead of repeating the same lines of code
again and again.
3) To give you a library of routines. You will do many things again, and again in your
career writing code. Writing a function to do it means that the next time you need to do
that particular manipulation you don’t need to rewrite that piece of code.
4) To save memory. When we create a function, we are only interested in the output of

SV MATLAB Solutions 9652458410 Anji Reddy


111
MATLAB fundamentals of programming
that function. All the other variables that are created within a function are only there in
order to help us get to that answer. The memory taken by these variables will be freed
once the function has terminated.

 Explain The MATLAB language?


This is a high-level matrix/array language with control flow statements, functions, data
structures, input/output, and object-oriented programming features. It allows both "programming
in the small" to rapidly create quick and dirty throw-away programs, and "programming in the
large" to create complete large and complex application programs.

 Can we run Matlab without graphics?


Sometimes you may want to run scripts which contain plotting commands without
displaying the plots and without going into the script to comment out the commands. An
example: if you're working from home and it's too slow to run graphics over the network. You
can play a simple UNIX trick: % setenv DISPLAY /dev/null % matlab

SV MATLAB Solutions 9652458410 Anji Reddy

You might also like