Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: matlab notes
Description: all and everything you need to learn MATLAB. basics, plots and graphs, image processing, animation, graphical user interfacing and much more
Description: all and everything you need to learn MATLAB. basics, plots and graphs, image processing, animation, graphical user interfacing and much more
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
MATLAB
Lesson 1
MATLAB BASICS
Introduction to MATLAB
The name MATLAB stands for MATrix LABoratory
...
MATLAB is a high-performance language for technical computing
...
Furthermore, MATLAB is a
modern programming language environment: it has sophisticated data structures, contains
built-in editing and debugging tools, and supports object-oriented programming
...
MATLAB has many advantages compared to conventional computer languages (e
...
, C,
FORTRAN) for solving technical problems
...
The software package has been
commercially available since 1984 and is now considered as a standard tool at most
universities and industries worldwide
...
It also has
easy to use graphics commands that make the visualization of results immediately available
...
There are toolboxes for
signal processing, symbolic computation, control theory, simulation, optimization, and
several other fields of applied science and engineering
...
When you start MATLAB, a special window called the MATLAB
desktop appears
...
The
major tools within or accessible from the desktop are:
• The Command Window
• The Command History
• The Workspace
• The Current Directory
• The Help Browser
• The Start button
MATLAB WINDOW
Get help
View or change
current directory
Move command
window outside of
desktop (undock)
Command window
Workspace
View or execute previously
run functions from the
command history window
...
(01) The graphical interface to the MATLAB workspace
When MATLAB is started for the first time, the screen looks like the one that shown in the
Figure (01)
...
You can customize the arrangement of tools and documents to suit your needs
...
We will assume that you have
sufficient understanding of your computer under which MATLAB is being run
...
Usually, there are 2 types of prompt:
• (>>)
: full version
• (EDU> )
: educational version
Note: To simplify the notation, we will use this prompt, >>, as a standard prompt sign
...
Let's start at the very beginning
...
You type it at the prompt command (>>) as follows,
>> 1+2*3
ans =
7
You will have noticed that if you do not specify an output variable, MATLAB uses a default
variable ans, short for answer, to store the results of the current calculation
...
(Or overwritten, if it is already existed) To avoid this, you may assign
a value to a variable or output argument name
...
This variable name can always be used to
refer to the results of the previous computations
...
0000
Before we conclude this minimum session, Table 1
...
Table (01): Basic arithmetic operators
Symbol
+
*
/
^
‘
Operation
Addition
Subtraction
Multiplication
Division
Power
Transpose
Example
2+3
2-3
2*3
2/3
3^2
A’
Quitting MATLAB
To end your MATLAB session, type quit in the Command Window, or select File
MATLAB in the desktop main menu
...
g
...
No explicit declaration of types is needed
...
Converting a fraction to an integer
•
•
•
round -nearest integerround(3
...
8) = 4
floor-nearest smaller integerfloor(3
...
14
i=square roote of (‐1)
inf=infinity
eps=2
...
element-wise
•
•
•
•
•
a + b addition;
a
...
/ b division;
a
...
matrix
• a + b addition;
• a –b subtraction;
• a * b multiplication ;
3
...
4
...
if not defined, m is always 1 by default
...
e
...
T=
1 2
3 4
then t(:) will give you
ans = 1
3
2
4
The LINSPACE operator
linspace(1,3,5) will give you output as [1 1
...
5 3]
here linspace (x, y, m) means x is starting value, y is maximum possible value
...
Subscripting matrices
in matrix a = [3 2 1; 6 5 4];
a(2,1) means 6
a(:,3) means all 3rd column numbers from all rows i
...
ans = 1
4
a(:,[3 1]) will give you output,
ans = 1 3
4 6
similarly
a (1,end) is 1
a (end,1) is 6
a (end,end) is 4
now create a 10x10 matrix and check the following command
a (3,1:4:end)
Matrices and Magic squares
In the MATLAB environment, a matrix is a rectangular array of numbers
...
MATLAB has other ways of storing both numeric and
nonnumeric data, but in the beginning, it is usually best to think of everything as a matrix
...
Where other
programming languages work with numbers one at a time, MATLAB allows you to work
with entire matrices quickly and easily
...
Start
by entering Dürer's matrix as a list of its elements
...
• Use a semicolon’;’ to indicate the end of each row
...
To enter Dürer's matrix, simply type in the Command Window
>>A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
MATLAB displays the matrix you just entered:
A=
16
5
9
4
3
10
6
15
2 13
11 8
7 12
14 1
This matrix matches the numbers in the engraving
...
You can refer to it simply as A
...
Why is it
magic?
Sum, Transpose and Diag
You are probably already aware that the special properties of a magic square have to do with
the various ways of summing its elements
...
Let us verify
that using MATLAB
...
Each of the
columns has the same sum, the magic sum, 34
...
For an additional way that avoids the double
transpose use the dimension argument for the sum function
...
The apostrophe operator (e
...
, A') performs a
complex conjugate transposition
...
The dotapostrophe operator (e
...
, A
...
For matrices containing all real elements, the two operators return the same result
...
But a function originally intended for
use in graphics, fliplr, flips a matrix from left to right:
>>sum(diag(fliplr(A)))
ans =
34
You have verified that the matrix in Dürer's engraving is indeed a magic square
...
For example, A(4,2) is the
number in the fourth row and second column
...
So to
compute the sum of the elements in the fourth column of A, type
>>A(1,4) + A(2,4) + A(3,4) + A(4,4)
This subscript produces
ans =
34
But is not the most elegant way of summing a single column
...
A single
subscript is the usual way of referencing row and column vectors
...
So, for the magic square, A(8) is
another way of referring to the value 15 stored in A(4,2)
...
Conversely, if you store a value in an element outside of the matrix, the size increases to
accommodate the newcomer:
>>X = A;
>>X(4,5) = 17
X=
16 3
2
5
10 11
9
6
7
4
15 14
13
8
12
1
0
0
0
17
The Colon Operator
The colon ‘:’ is one of the most important MATLAB operators
...
The expression
>>1:10
is a row vector containing the integers from 1 to 10
ans =
1 2 3 4 5 6 7 8 9 10
To obtain non unit spacing, specify an increment
...
Not
surprisingly, this function is named magic:
>>B = magic (4)
B=
16
2
3
13
5
11
10
8
9
7
6
12
4
14
15
1
This matrix is almost the same as the one in the Dürer engraving and has all the same
"magic" properties; the only difference is that the two middle columns are exchanged
...
It produces:
A=
16
3
2
13
5
10
11
8
9
6
7
12
4
15
14
1
Expressions
Variables
Like most other programming languages, the MATLAB language provides mathematical
expressions, but unlike most programming languages, these expressions involve entire
matrices
...
When MATLAB
encounters a new variable name, it automatically creates the variable and allocates the
appropriate amount of storage
...
For example,
num_students = 25
Creates a 1-by-1 matrix named num_students and stores the value 25 in its single element
...
MATLAB is case
sensitive; it distinguishes between uppercase and lowercase letters
...
Numbers
MATLAB uses conventional decimal notation, with an optional decimal point and leading
plus or minus sign, for numbers
...
Imaginary numbers use either i or j as a suffix
...
0001
9
...
60210e-20 6
...
14159j 3e5i
All numbers are stored internally using the long format specified by the IEEE® floating-point
standard
...
Working with matrices
The load Function
The load function reads binary files containing matrices generated by earlier MATLAB
sessions, or reads text files containing numeric data
...
For example, outside of MATLAB, create a text file
containing these four lines:
16
...
0
2
...
0
5
...
0 11
...
0
9
...
0
7
...
0
4
...
0 14
...
0
Save the file as magik
...
The statement
load magik
...
M‐Files
You can create your own matrices using M-files, which are text files containing MATLAB
code
...
Save the file under a name that
ends in
...
For example, create a file in the current directory named magik
...
0
5
...
0
4
...
0
10
...
0
15
...
0
11
...
0
14
...
0
8
...
0
1
...
Concatenation
Concatenation is the process of joining small matrices to make bigger ones
...
For an example,
>>B = [A A+32; A+48 A+16]
The result is an 8-by-8 matrix, obtained by joining the four sub matrices:
B=
16
5
9
4
64
53
57
52
3
10
6
15
51
58
54
63
2
11
7
14
50
59
55
62
13
8
12
1
61
56
60
49
48
37
41
36
32
21
25
20
35
42
38
47
19
26
22
31
34
43
39
46
18
27
23
30
45
40
44
33
29
24
28
17
This matrix is halfway to being another magic square
...
Its column sums are the correct value for an 8-by-8 magic square:
>>sum(B)
ans =
260 260 260 260 260 260 260 260
But its row sums, sum (B')', are not all the same
...
Deleting Rows and Columns
You can delete rows and columns from a matrix using just a pair of square brackets
...
So,
expressions like
>>X(1,2) = []
Result in an error
...
So
>>X(2:2:10) = []
results in
X=
16
9
2
7
13
12
1
The Find Function
Find function finds indices and value of nonzero elements
...
>>x=[1 0 4 -3 0 0 0 8 6];
>>Ind=find(x)
Ind=
1 3 4 8 9………………………… [Index of nonzero elements]
>>Ind=find(x>4)
Ind=
8 9……… [Gives index of those elements which are nonzero and also greater than 4]
Ind=find(x,k) or Ind=find(x,k,’first’): K is positive integer
...
>>Ind=find(x,3)
Ind=
134
Ind=find(x,k,’last’): K is positive integer
...
>>Ind=find(x,3,’last’)
Ind=
489
Controlling Command Window Input and Output
The Format Function
The format function controls the numeric format of the values displayed
...
Here
are the different formats, together with the resulting output produced from a vector x with
components of different magnitudes
...
2345e-6]
x=
1
...
0000
>>format long
>>x = [4/3 1
...
33333333333333
>>format bank
>>x = [4/3 1
...
33
0
...
2345e-6]
x=
4/3
1/810045
0
...
2345e-6]
x=
3ff5555555555555
3eb4b6231abfd271
In addition to the format functions shown above format compact suppresses many of the
blank lines that appear in the output
...
Suppressing Output
If you simply type a statement and press Return or Enter, MATLAB automatically displays
the results on screen
...
This is particularly useful when you generate
large matrices
...
, followed by Return
or Enter to indicate that the statement continues on the next line
...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
MATLAB
Lesson 2
Operators
Loops
& Conditional
statements
Logical Expressions
A logical expressionis one that evaluates to either true or false
...
Logical expressions can be assigned to Boolean variables
...
is v is greater than 0 then s will
store the value 1 else 0
...
i
...
c = 5
...
a & b
2
...
a ~=b
4
...
1 1
0 1
2
...
1 0
0 1
4
...
a = [ 1 0 -1 5 8 9 ]
b = [ 1 -2 -2 5 8 11 ]
a == b will return
[100110]
find(a == b) will return
[145]
Conditional operations
Conditional operations act like program switches which respond to certain conditions within
the program
...
Two alternatives require the
construction
if expression
commands (evaluated if expression is true)
else
commands (evaluated if expression is false)
end
If there are several alternatives one should use the following construction
if expression1
commands (evaluated if expression 1 is true)
elseif expression 2
commands (evaluated if expression 2 is true)
elseif …
...
5
disp('lucky!')
else
disp(‘unlucky!')
end
see the output of above code writing the code in
...
Write MATLABcode for the “GUESS MY NUMBER” game
...
The computer picks a random integer between 1 and 10
...
The user is asked to guess the number
...
3
...
% MATLABcode for the GUESS MY NUMBER game
...
')
elseifceil(UserGuess) ~= floor(UserGuess)
disp('ERROR -Your number must be integer
...
otherwise
statements
end
Switch compares the input expression to each case value
...
In the following example a random integer number x from the set
{1, 2, … , 10} is generated
...
If x = 3 or 4 or 5, then the message Probability = 30% is displayed, otherwise
the message Probability = 50% is generated
...
% Script file fswitch
...
, 10}
switch x
case {1,2}
disp('Probability = 20%');
case {3,4,5}
disp('Probability = 30%');
otherwise
disp('Probability = 50%');
end
Note use of the curly braces after the word case
...
Here are new
MATLAB functions that are used in file fswitch
...
The for loops can be nested
%PREPARE SCRIPT FILE FOR THE FOLLOWING CODE
H = zeros(5);
for k=1:5
for l=1:5
H(k,l) = 1/(k+l-1);
end
end
H %SIMPLY ENTER IT IN COMMAND WINDOW TO CHECK THE O/P
H=
1
...
5000 0
...
2500 0
...
5000 0
...
2500 0
...
1667
0
...
2500 0
...
1667 0
...
2500 0
...
1667 0
...
1250
0
...
1667 0
...
1250 0
...
First command assigns a space in
computers memory for the matrix to be generated
...
WHILE LOOP
Syntax of the while loop is
while expression
statements
end
This loop is used when the programmer does not know the number of repetitions a priori
...
Suppose that the number _ is
divided by 2
...
This process is continued till the
current quotient is less than or equal to 0
...
What is the largest quotient that is greater than
0
...
01
q = q/2;
end
q %ENTER IT IN COMMAND WINDOW
q=
0
...
for k = 1:0
...
for k = 1:-0
...
write the code for following output
-3
-2
...
5
-1
-0
...
5
4
...
The “figure” command will open an empty new figure
...
If you want to plot more than one graph on the same figure, use the
command HOLD
ON
3
...
To make the axis square, type AXIS SQUARE
5
...
You can edit manually the figure, add text and lines by clicking on the arrow
in the
figure’s menu line
...
You can copy and paste MATLAB figures in Word and Powerpoint
documents
...
Parameters for plotting the graph (in ‘ ’)
y yellow
m magenta
c cyan
r red
g green
b blue
w white
k black
...
dashdot
‐‐ dashed
p pentagram
h hexagram
example
plot(1,1,’g+’);
Some useful commands:
commands
use
example
legend
Graph legend
legend('first wave','second wave')
title
Graph title
title(‘sine wave’)
xlabel
X‐axis label
xlabel(‘time’)
ylabel
Y‐axis label
ylabel(‘amplitude’)
text
Text annotation
text(0,1,’this is test’)
gtext
Place text with mouse gtest(‘this is mouse test’)
Fill
Fill the color
fill(x,y,’r’)
Try this example and observe the output after each comand:
x = ‐pi:pi/10:2*pi
y=sin(x)
plot(x,y,'rs‐‐','LineWidth',2,
...
'MarkerFaceColor','g',
...
To draw a shape you have to give its x and y points
...
25);
y3 = sin(t‐0
...
25)’,’sin (t‐0
...
For example, the command
set(0,'DefaultAxesLineStyleOrder',{'‐o',':s','‐‐+'})
defines three line styles and makes them the default for all plots
...
4,0
...
4])
The default values persist until you quit MATLAB
...
set(0,'DefaultAxesLineStyleOrder','remove')
set(0,'DefaultAxesColorOrder','remove')
Figure Window
Graphing functions automatically open a new figure window if there are no
figure
windows already on the screen
...
If there are multiple figure windows open, MATLAB targets
the one that is
designated the “current figure” (the last figure used or clicked in)
...
The results of subsequent
graphics
commands are displayed in this window
...
However, these commands do not reset figure
properties, such
as the background color or the color map
...
Typing
subplot(m,n,p)
partitions the figure window into an m‐by‐n matrix of small subplots and
selects the
pth subplot for the current plot
...
For example, these statements plot
data in four
different sub regions of the figure window
...
Each character is represented internally by its ASCII value
...
'
str =
I am learning MATLAB this semester
...
To compare two strings for equality use function strcmp
>>iseq = strcmp(str, str2)
iseq =
1
Two strings can be concatenated using function strcat
>>strcat(str,str2)
ans =
I am learning MATLAB this semester
...
Note that the concatenated strings are not separated by the blank space
...
g
...
; : etc) in string a
Remove leading and trailing
unseen characters from
string a
Checks if a is a string
Converts string of digits (a)
to a number
Converts number to a string
of digits (a)
Display the string a on
command window, takes
input from user and stores it
in variable k
Takes input from user in
string format
Write formatted data to a
string
...
%s = string, see help for full
details
Write the formatted data on
command window
Display variable a in
command window
Result
1 if identical, 0 if not
Array of start positions for
each occurrence of b
The new version of string a
The section of a that occurs
before the token character
The new version of string a
1 is a string, 0 if not
The number as a double data
type
The string
The formatted string
examples for string:
name = input('Enter your name: ', 's'); % get name
age = input('Enter your age: ') % get age
s = sprintf('%s is %d years old\n', name, age);
disp(s) % display the string
more on:
Example of String Manipulation: Count the number of a given character within a given
word (e
...
, letters “S” in “MISSISSIPPI”)
clc% clear the screen
m = input('String = ','s'); % MISSISSIPPI
c = input('Character = ','s'); % S
positions_of_c= strfind(m,c); % find positions of c in m
fprintf('Number of ''%s'' in ''%s'' is %d\n',
...
write a code to accept a name and contact number from user and display it on
command window like: when user inputs suresh and 12345
your name is : suresh
your contact number is: 12345
2
...
suppose variable a has ‘matlab’ and b has ‘matlab matlab’
compare a and b and display they are equal or not
MATLAB
Lesson 5
Random Data
and
Functions
Data:
WORKING WITH RANDOM DATA
some functions to generate random numbers:
rand
rand(rows, columns)
randi(maxn)
randi(maxn,rows,columns)
generates a random number between 0 and 1
generates a random matrix with numbers between 0 and 1
generates a random integer between 1 and maxn
generates a random matrix with integers between 1 and maxn
figure
hold on
for i = 1:300
x = rand;
plot([x x],[0 1],'k-')
pause(0
...
and state the difference
figure(3)
hold on
for i = 1:300
x = rand;
y = rand;
plot(x,y,'kd')
pause(0
...
05)
end
to generate the list of n numbers with mean m and standard deviation d,
arr=m+d*randn(1,n);
randperm(n)
...
example:
1
...
to generate random index:
Let D be an array as shown below
...
D = {‘Monday’, ‘Tuesday’, ‘Wednesday’ , ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Sunday’ };
var3= randperm(numel(D));
disp(D(var3(1:2)));
do it yourself:
1
...
Arrange the elements of A in random order
...
Select randomly half of the elements of array A and put them in array B
...
Let P be a 2-dimensional array
...
rp= randperm(size(P,1));
Q = P(rp(1:K),:)
4
...
Q = P(randi(size(P,1),K,1),:);
Statistical Data manipulation:
let’s consider a vector
a=[4 5 2 10 -5 19 19 27]
hence sorted vector will be
a=[-5 2 4 5 10 19 19 27]
now we will apply statistical definations on the vector a:
mean(a) : sum of all elements and divide it by total number of elements=10
...
5
mode(a): number appears maximum time= 19
min(a): minimum number in list = -5
max(a): maximum number in list= 27
range(a): difference of min and max = 32
std(a): standard deviation
try this and figure out whats going on in the code:
a=[1 5 9;4 3 6;9 8 1;2 5 6];
[p,q] = min(a);
to display statistical data in figure format like bar graph or histogram,
there are commands :
Functions:
A function is a group of statements that together perform a task
...
How you divide up your code among different functions is up
to you, but logically the division usually is so each function performs a specific task
...
For example,
function strcat() to concatenate two strings, function strcmp() to compare two strings and
so on
A function is known with various names like a method or a sub‐routine or a procedure, etc
...
and for each function you have to
define different m file
...
(provided: name of function must be add and it will store the result in variable sum)
solution:
function sum= add(a,b)
sum=a+b;
fprintf('addition of %d and %d is %d\n',a,b,sum);
end
Observe the code
...
function [output_variables_list] = [function_name] ([input parameters])
%dont consider [] brackets
...
Write a Maltab function which will take a square matrix and will display in the
command window the lower triangular part:
solution:
function lower_triangle(a)
[m,n] = size(a);
if m ~= n
error ('The input matrix is not square')
end
fprintf('\n')
for i= 1:m
for j = 1:i
fprintf('%10
...
write functions for subtraction, multiplication and division of two numbers
2
...
use above functions
...
output of program should be as follows:
MATLAB
Lesson 6
GUI
Graphical
User
Interface
Using
MATLAB
Table of contents:
1
...
3
2
...
4
• Opening a new GUI in the Layout Editor……………………
...
5
• Adding the components……………………………………………… 5
• Aligning the components……………………………………………
...
8
• Completed Layout……………………………………………………
...
10
3
...
12
• Adding Code to the GUI…………………………………………… 12
• Programming the push buttons……………………………… 12
• Complete code………………………………………………………
...
Running the GUI……………………………………………………………… 17
Example of Graphical User Interfacing
The GUI contains:
An axes component
• two edit text components to give two inputs and one
component for output
• three static text components to label the edit text components
• five push buttons, for addition, subtraction, multiplication,
division and clear screen respectively
To use the GUI, give two numbers in first and second text boxes and
click on any one button for mathematical operation i
...
addition,
subtraction, multiplication or division
...
Laying Out a Simple GUI
Opening a New GUI in the Layout Editor
1
...
The GUIDE
Quick Start dialog displays, as shown in the following figure
...
Click OK to display the blank GUI in the Layout Editor, as shown in
the following figure
...
Then select GUIDE > Show
names in component palette, and click OK
...
Click the lower‐right corner and drag it until the GUI is approximately
3 in
...
wide
...
Adding the Components
1
...
Select the edit text
tool from the component palette at the left side of the Layout Editor
and drag it into the layout area
...
2
...
Add the remaining components to the GUI
...
Aligning the Components
If several components have the same parent, you can use the
Alignment Tool to align them to one another
...
Select all three edit text by pressing Ctrl and clicking them
...
Select Align Objects from the Tools menu to display the
Alignment Tool
...
Make these settings in the Alignment Tool, as shown in the
following figure:
• 20 pixels spacing between edit text in the vertical direction
...
and click OK
...
Their text is generic, for example Push Button 1
...
This topic shows you how to modify the
default text
...
Labeling the Push Buttons
Each of the five push buttons lets the GUI user choose the
mathematical operation to perform: addition, subtraction,
multiplication, division
...
1
...
2
...
3
...
4
...
Label the buttons as ‐, *, / and C
5
...
6
...
Saving the GUI Layout
When you save a GUI, GUIDE creates two files, a FIG‐file and a code
file
...
fig, is a binary file that contains a
description of the layout
...
m, contains
MATLAB functions that control the GUI
...
Save and activate your GUI by selecting Run from the Tools menu
...
GUIDE displays the following dialog box
...
4
...
5
...
GUIDE saves both the
FIG‐file and the code file using this name
...
If the folder in which you save the GUI is not on the MATLAB path,
GUIDE opens a dialog box, giving you the option of changing the
current folder
...
GUIDE saves the files calculator
...
m and activates
the GUI
...
The GUI opens in a new window
...
You can add your own menus and toolbar buttons with GUIDE, but
by default a GUIDE GUI includes none of these components
...
>>calculator
or run calculator
Programming a Simple GUI
Adding Code to the GUI
When you saved your GUI in the previous topic, Saving the GUI
Layout, GUIDE created two files: a FIG‐file calculator
...
m that contains the code that
controls how the GUI behaves
...
Programming the Push Buttons:
1
...
From that
menu, select View Callbacks > Callback
...
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)
1
...
edit1,'String'));
second_num=str2double(get(handles
...
edit3,'String',answer);
2
...
3
...
4
...
edit1,'String',answer);
set(handles
...
edit3,'String',answer);
5
...
Complete code
so this is the working code for calculator
...
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)
first_num=str2double(get(handles
...
edit2,'String'));
answer=first_num+second_num;
set(handles
...
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved ‐ to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
first_num=str2double(get(handles
...
edit2,'String'));
answer=first_num‐second_num;
set(handles
...
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved ‐ to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
first_num=str2double(get(handles
...
edit2,'String'));
answer=first_num*second_num;
set(handles
...
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)
first_num=str2double(get(handles
...
edit2,'String'));
answer=first_num/second_num;
set(handles
...
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)
answer='';
set(handles
...
edit2,'String',answer);
set(handles
...
Check all the
functions before closing the GUI
...
So MATLAB saves image in the form of numbers and process the data
accordingly
...
now we will see how to read the image as data matrix for processing in MATLAB
A = imread('image1
...
above command will create three matrices
for red green and blue color
...
to convert it into gray,
B = rgb2gray(A); % A is matrix of some image as above
imshow(B);
Similarly to convert colored image into black and white,
B = im2bw(A); % A is matrix of some image as above
imshow(B);
(Note:
1
...
remaining
numbers inbetween for gray
2
...
3
...
i
...
(255,0,0), in green pane, 255 is for green, and in blue,255 for blue
...
Write MATLAB code to colour the top border of
the image in red and display the image
...
a normal RGB image and also gray
image(Assume matrix A contains the image )
B = rgb2gray(A);
imshow([fliplr(B) B]);
A1 = A(:,:,1);
A2 = A(:,:,2);
A3 = A(:,:,3);
B(:,:,1) = fliplr(A1);
B(:,:,2) = fliplr(A2);
B(:,:,3) = fliplr(A3);
imshow([A B]);
example 3:
try this and find out what function flipdim is
imshow([flipdim(A,2) A])
example 4:
write a code to make the full image in green
A(:,:,2) = 255;
imshow(A);
example 5:
Construct by hand an image that looks like a simple drawing of a house
...
(See Examples for an illustration
...
Each element of C corresponds to a rectangular area in the image
...
but colours of each patch are randomly chosen
...
example:
arr=[1 2 3 1 ];
imagesc(arr);
this code will create an image which has four patches and first and last patches are with
same colours
...
and now change the colour for following diagram:
Now do the above exercise of creating home
...
• Continually erase and then redraw the objects on the screen, making incremental
changes with each redraw
...
example 1:
figure
h = plot(0,0,'k
...
this code will create a circle in the centre with black color
...
it says
h= and then plotting of data, so that that it will store in ‘h’
...
and this data we can use in next instructions also
...
for i = 1:100
set(h,'XData',randn)
set(h,'YData',randn,'color',rand(1,3))
pause(0
...
your object is now handled by ‘h’
...
to check the latest properties of h, type
get(h)
...
so it is changing its place
...
experiment 1: now just try to change color only and not place
...
01
for i = 1:100
set(h,'XData',randn*0
...
01,'color',rand(1,3))
pause(0
...
The movement along the edges should be
visible!
solution:
figure,hold on
h = plot(0,0,'r
...
3 1
...
3 1
...
01),end
example 3:
Make the point visit all 4 corners of the unit square clockwise
...
','markersize',100);
plot([0 1 1 0 0],[0 0 1 1 0],'k‐')
axis([‐0
...
3 ‐0
...
3])
axis square
grid on
steps = linspace(0,1,100);
for i = 1:100, set(h,'YData',steps(i)),pause(0
...
01),end
for i = 1:100, set(h,'YData',steps(101‐i)),pause(0
...
01),end
now try this yourself
1
...
The movement
along the edges should be visible!
2
...
make the whole process
slower than above example without changing pause
3
...
4
...
5
...
6
...
7
...
sun is steady and planet is moving around it in
circular orbit
...
8
...
4 seconds
...
Tic starts the
stopwatch and toc ends it
...
TIC saves the current
time that TOC uses later to measure the elapsed time
...
t = toc;
will save the elapsed time (in seconds) in t
...
CPUTIMEreturns the CPU time in seconds that has been used
by the MATLABprocess since MATLABstarted
...
The handle to the waitbarfigure is
returned in h
...
');
for i= 1:1000,
% computation here %
waitbar(i/1000,h)
end
close (h);
Mouse control
T = waitforbuttonpress
stops program execution until a key or a mouse button is pressed over a figure window
...
How do we check whether the mouse has clicked over an object?
gco= “get current object”
If the mouse has been over an object, gcocontains the handle of this object, otherwise, it
contains the handle of the “parent” (which will be the figure)
So when we click on figure and not on object, it will return 1, otherwise a value
...
And write a code to
check whether user has click on that triangle or on figure
...
The object to be caught by the
mouse click is a triangle with random vertices and random colour
...
A new triangle is displayed after each mouse
click
...
The time should be displayed after the
10 hits are completed
...
7,0
...
2f s',time10hits));
set(t,'FontName','TrebuchetMS','Fontsize',16)
modify the same code to record the lowest time taken by user
...
Go through the following code:
figure, hold on, axis([0 1 0 1]), axis square, grid on
if waitforbuttonpress == 0
point = get(gca,'CurrentPoint');
plot(point(1,1),point(1,2),'m*‐');
end
now modify the above code for following:
write a code which will plot the points which are indicated by mouse
...
After pressing a key, program will stop
...
‐')
last = point;
end
and now try the following code:
Enter a shape with the mouse and fill it with purple
...
)
[X,Y] = GINPUT(N) gets N points from the current axes and returns the X‐and Y‐coordinates
in length N vectors X and Y
...
[X,Y] = GINPUTgathers an unlimited number of points until the return key is pressed
...
Examples:
[x,y] = ginput;
[x,y] = ginput(5);
[x, y, button] = ginput(1);
Example: What does this code do?
clear all
close all
clc
figure('color','k')
axes('Position',[0 0 1 1]), hold on
axis([‐1 2 ‐1 2],'off')
for i= 1:15
pl = ginput(1);
fill(pl(1)+rand(1,3)‐0
...
5,
...
In Model‐Based Design, a system model is at the center of the development
process, from requirements development, through design, implementation, and testing
...
After model development, simulation shows whether the model works correctly
...
Model‐Based Design allows you to improve efficiency by:
•
•
•
•
•
•
•
•
Using a common design environment across project teams
Linking designs directly to requirements
Integrating testing with design to continuously identify and correct errors
Refining algorithms through multi‐domain simulation
Automatically generating embedded software code
Developing and reusing test suites
Automatically generating documentation
Reusing designs to deploy systems across multiple processors and hardware targets
Modeling Process
There are six steps to modeling any system:
1
...
3
...
5
...
Defining the System
Identifying System Components
Modeling the System with Equations
Building the Simulink Block Diagram
Running the Simulation
Validating the Simulation Results
You perform the first three steps of this process outside of the Simulink software before you
begin building your model
...
If you are modeling
a large system that can be broken into parts, you should model each subcomponent on its
own
...
For example, the demo model used later in this guide models the heating system of a house
...
Identifying System Components
The second step in the modeling process is to identify the system components
...
For each subsystem that you identified, ask yourself the following questions:
•
•
•
•
•
How many input signals does the subsystem have?
How many output signals does the subsystem have?
How many states (variables) does the subsystem have?
What are the parameters (constants) in the subsystem?
Are there any intermediate (internal) signals in the subsystem?
Once you have answered these questions, you should have a comprehensive list of the
system components, and are ready to begin modeling the system
...
For each subsystem, use the list of system components you identified to describe the
system mathematically
...
Building the Simulink Block Diagram
After you have defined the mathematical equations that describe each subsystem, you can
begin building a block diagram of your model in Simulink
...
After you have
modeled each subcomponent, you can then integrate them into a complete model of the
system
...
Simulink allows you to interactively define system inputs, simulate the model, and observe
changes in behavior
...
Validating the Simulation Results
Finally, you must validate that the model accurately represents the physical characteristics
of the system
...
Exercise 1:
Create a simulink model which will add two constants using add block
...
our system will look like the following figure:
Now we will create a simulink model which will look similar
...
Exercise 2:
Create a simulink model to generate a sine wave of amplitude 4V and frequency 1 Hz
...
Solution:
Block diagram:
Simulink Model:
•In the new model, add following blocks:
Sine wave (sources)
scope (sinks)
• Double click on sine wave and change the amplitude and frequency as required
...
Exercise 3:
Create a simulink model to generate a pulse
...
try changing various
parameters of pulse generator
Title: matlab notes
Description: all and everything you need to learn MATLAB. basics, plots and graphs, image processing, animation, graphical user interfacing and much more
Description: all and everything you need to learn MATLAB. basics, plots and graphs, image processing, animation, graphical user interfacing and much more