0% found this document useful (0 votes)
4 views

Matlab

Uploaded by

mikyyeheyes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Matlab

Uploaded by

mikyyeheyes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Basics of MATLAB

What is Matlab?
• Matlab is basically a high level language which
has many specialized toolboxes for making
things easier for us
• How high?
Matlab

High Level
Languages such as
C, Pascal etc.

Assembly
Starting MATLAB
• Matlab (matrix laboratory) is a software package that lets you
do mathematics and computation, analyze data, develop
algorithms, do simulation and modeling, and produce
graphical displays and graphical user interfaces.
• To run matlab on a PC double- click on the matlab icon.
• You get matlab to do things for you by typing in commands.
• You can type help at the matlab prompt, or pull down the Help
menu on a PC.
• The various forms of help available are
• Help win opens a matlab help GUI (graphical user interface)
• Help desk opens a hypertext (text displayed on a computer
display) help browser
• Demo starts the matlab demonstration
Contd…
• You can learn how to use any matlab command by typing help
followed by the name of the command, for example, help sin.
• You can also use the look for command, which searches the help
entries for all matlab commands for a particular word.
First Steps
• To get matlab to work out 1 + 1, type the following at the prompt
(command window):
• you have started MATLAB on your system successfully and you
are ready to type the commands at the MATLAB prompt (which
is denoted by double arrows “>>”). Entering scalars and simple
operations is easy as is shown in the examples below:
x= 1+1
ans =
2
>> 2/sqrt(3+x)
• To suppress the output in MATLAB use a semicolon to end the
command line as in the following examples. If the semicolon is
not used then the output will be shown by MATLAB:
» y=32;
» z=5;
» x=2*y-z;
» w=3*y+4*z
w=
116
• MATLAB is case-sensitive, i.e. variables with lowercase letters
are different than variables with uppercase letters. Consider
the following examples using the variables x and X.
Matlab Screen
• Command Window
– type commands

• Current Directory
– View folders and m-files

• Workspace
– View program variables
– Double click on a variable
to see it in the Array Editor

• Command History
– view past commands
– save a whole session
using diary
Contd…

• The answer to the typed command is given the name ans. In


fact ans is now a variable that you can use again. For example
you can type ans*ans to check that 2×2=4: ans*ans
ans =
4
• The spacing of operators in formulas does not matter. The
following formulas both give the same answer:
1+3 * 2-1 / 2*4
1+3*2-1/2*4
• The order of operations is made clearer to readers of your
matlab code if you type carefully:
1 + 3*2 - (1/2)*4
Matrices
• The basic object that matlab deals with is a matrix. A matrix is
an array of numbers. For example the following are matrices:

Typing Matrices
To type a matrix in to matlab you must
• Begin with a square bracket[
• Separate elements in a row with commas or spaces
• Use a semi colon ; to separate rows
• End the matrix with another square bracket].
Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose
For example type:
a = [1 2 3; 4 5 6;7 8 9]
matlab responds with
a=
1 2 3
4 5 6
7 8 9
• Matrices can be made up of sub matrices: Try this:
>> b = [a 10*a;-a [1 0 0; 0 1 0;0 0 1]]
b=
Contd…

The repmat function can be used to replicate a matrix:


>>a=[1 2;3 4]
a=
1 2
3 4
>> repmat (a,2,3)
ans =
Useful Matrix Generators
Matlab provides four easy ways to generate certain simple
matrices. These are
• zeros a matrix filled with zeros
• ones a matrix filled with ones
• rand a matrix with uniformly distributed random elements
• randn a matrix with normally distributed random elements
• eye identity matrix
To tell matlab how big these matrices should be you give the
functions the number of rows and columns. For example:
Contd…

Subscripting
• Individual elements in a matrix are denoted by a row
index and a column index. To pick out the third element
of the vector u type:
>> u (3)
ans =
0.1763
Contd…

You can use the vector [1 2 3] as an index to u.


To pick the first three elements of u type
>> u ([1 2 3])
ans =
0.9218 0.7382 0.1763
Remembering what the colon operator does, you can abbreviate
this to
Contd…
Contd…

• The last two examples use the colon symbol as an index, which
matlab interprets as the entire row or column. If a matrix is
addressed using a single index, matlab counts the index down
successive columns:
>> a(4)
ans =
2
>> a(8)
ans =
6
End as a subscript
To access the last element of a matrix along a given dimension, use
end as a subscript. This allows you to go to the final element
without
knowing in advance how big the matrix is.
Example:

Deleting Rows or Columns


To get rid of a row or column set it equal to the empty matrix [].
Examples
Transpose
• To convert rows into columns use the transpose symbol’:
Contd…

Or
Basic Graphics
• The bread-and-butter of matlab graphics is the plot command.
Earlier we produced a plot of the sine function:

• There are many options for changing the appearance of a plot. For
example: plot(x,y,’r-.’) will join the points using a red dash-dotted
line.
• Other colours you can use are: ’c’, ’m’, ’y’, ’r’, ’g’, ’b’, ’w’, ’k’,
which correspond to cyan, magenta, yellow, red, green, blue, white,
and black. Possible line styles are: solid ’-’, dashed ’--’, dotted ’:’,
and dash-dotted ’-.’. To plot the points themselves with symbols you
can use: dots’.’, circles ’o’, plus signs ’+’, crosses ’x’, or stars ’*’,
and many others (type help plot for a list).
Plotting Many Lines
• To plot more than one line you can specify more than one set
of x and y vectors in the plot command:
Plotting Matrices

• If one of the arguments to the plot command is a matrix,


matlab will use the columns of the matrix to plot a set of lines,
one line per column:
Contd…
• Matlab plots the columns of the matrix q against the row index. You
can also supply an x variable:

Subplots
• To plot more than one set of axes in the same window, use the
subplot command. You can type subplot (m,n,p) to break up the
plotting window into m plots in the vertical direction and n plots in
the horizontal direction, choosing the pth plot for drawing in to.
Three-Dimensional Plots
• The plot3 command is the 3-d equivalent of plot:
Basic Task: Plot the function sin(x) between
0≤x≤4π
• Create an x-array of 100 samples between 0 and
4π.

>>x=linspace(0,4*pi,100);

• Calculate sin(.) of the x-array 1

0.8

0.6

>>y=sin(x); 0.4

0.2

• Plot the y-array


-0.2

-0.4

-0.6

>>plot(y) -0.8

-1
0 10 20 30 40 50 60 70 80 90 100
Plot the function e-x/3sin(x) between 0≤x≤4π

• Create an x-array of 100 samples between 0


and 4π.
>>x=linspace(0,4*pi,100);

• Calculate sin(.) of the x-array


>>y=sin(x);

• Calculate e-x/3 of the x-array


>>y1=exp(-x/3);

• Multiply the arrays y and y1


>>y2=y*y1;
Plot the function e-x/3sin(x) between 0≤x≤4π

• Multiply the arrays y and y1 correctly


>>y2=y.*y1;

• Plot the y2-array


0.7

>>plot(y2) 0.6

0.5

0.4

0.3

0.2

0.1

-0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities
0.7

0.6

• plot(.)
0.5

0.4

0.3

Example:
0.2

0.1
>>x=linspace(0,4*pi,100); 0

>>y=sin(x); -0.1

>>plot(y) -0.2

>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100

0.7

• stem(.) 0.6

0.5

0.4

0.3

Example:
0.2

0.1
>>stem(y) 0

>>stem(x,y) -0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities
• title(.)
This is the sinus function
>>title(‘This is the sinus function’) 1

0.8

• xlabel(.) 0.6

0.4

>>xlabel(‘x (secs)’) 0.2

sin(x)
0

• ylabel(.)
-0.2

-0.4

-0.6

-0.8
>>ylabel(‘sin(x)’) -1
0 10 20 30 40 50 60 70 80 90 100
x (secs)
PROGRAMMING IN MATLAB

• To take advantage of MATLAB’s full capabilities, we need to


know how to construct long (and sometimes complex)
sequences of statements. This can be done by writing the
commands in a file and calling it from within MATLAB.
• Such files are called “m-files” because they must have the file
name extension “.m”. This extension is required in order for
these files to be interpreted by MATLAB.
• There are two types of m-files: script files and function files.
• Script files contain a sequence of usual MATLAB commands,
that are executed (in order) once the script is called within
MATLAB.

Contd…

• Function files, on the other hand, play the role of user defined
commands that often have input and output. You can create
your own commands for specific problems this way, which
will have the same status as other MATLAB commands.
function [a] = log3(x)
% [a] = log3(x) - Calculates the base 3 logarithm of x.
a = log(abs(x))./log(3);
% End of function
Loops
• The two types of loops that we will discuss are “for” and
“while” loops. Both loop structures in MATLAB start with a
keyword such as for, or while and they end with the word end.
Contd…
• The “for” loop allows us to repeat certain commands. If you want to
repeat some action in a predetermined way, you can use the “for” loop.
The “for” loop will loop around some statement, and you must tell
MATLAB where to start and where to end.
For example,
>> for j=1:4
j+2
end

A=[1,5,-3;2,4,0;-1,6,9];
» for i=1:3
for j=1:3
A2(i,j) = A(i,j)^2;
end
end
If statement

• There are times when you would like your algorithm/code to


make a decision, and the “if” statement is the way to do it.
The general syntax in MATLAB is as follows:
if relation
statement(s)
else if relation % if applicable
statement(s) % if applicable
else % if applicable
statement(s) % if applicable
end
• Let us illustrate the “if” statement through a simple example.
Suppose we would like to define and plot the piecewise
defined function.

• This is done with the use of the “if” statement in MATLAB as


follows. First we define the “domain” vector x from –1 to 1
with increment 0.01 to produce a smooth enough curve.
Contd…

• Finally, we plot the two vectors (using a solid black curve).


» plot(x,F,’-k’)
Example for spring

Step 1 – Discretizing the Domain:


• The domain is subdivided into two elements and three nodes.
Step 2 – Writing the Element Stiffness Matrices:
• The two element stiffness matrices k1 and k2 are obtained by
making calls to the MATLAB. Each matrix has size2×2.
Step 3 – Assembling the Global Stiffness Matrix:
• Since the spring system has three nodes, the size of the global
stiffness matrix is3×3.Therefore to obtain K we first set up a zero
matrix of size 3×3 then make two calls to the MATLAB function
Spring Assemble since we have two spring elements in the system .

Step 4 – Applying the Boundary Conditions:


Step 5 – Solving the Equations:

Step6–Post-processing:
• In this step, we obtain the reaction at node 1 and the force in
each spring using MATLAB.
• First we set up the global nodal displacement vector U, then
we calculate the global nodal force vector F
Problem 1
• Consider the spring system composed of two springs as
shown. Given k1= 200kN/m, k2= 250kN/m, and P=10kN,
determine:
1. The global stiffness matrix for the system.
2. The displacements at node 2.
3. The reactions at nodes 1 and 3.
4. The force in each spring
Example2

Consider the plane truss shown. Given E= 210GPa and


A=1×10−4m2,determine:
1. the global stiffness matrix for the structure.
2. the horizontal displacement at node 2.
3. the horizontal and vertical displacements at node 3.
4. the reactions at nodes 1 and 2.
Step 1 – Discretizing the Domain

Step 2 – Writing the Element Stiffness Matrices


• The three element stiffness matricesk1, k2, and k3are obtained
by making calls to the MATLAB. Each matrix has size4×4
Contd…

Step 3 – Assembling the Global Stiffness Matrix:


• Since the structure has three nodes, the size of the global
stiffness matrix is6×6. Therefore to obtain K we first set up a
zero matrix of size 6×6 then make three calls to the MATLAB
since we have three elements in the structure. Each call to the
function will assemble one element.
Step 4 – Applying the Boundary Conditions:

• The matrix for this structure is obtained as follows using the


global st.iffness matrix obtained in the previous step
Contd…
• Inserting the above conditions into the matrices we obtain:

Step 5 – Solving the Equations:


• Solving the system of equations in the above will be performed
by partitioning (manually) and Gaussian elimination (with
MATLAB). Therefore we obtain:
Step6–Post-processing:

• In this step, we obtain the reactions at nodes 1 and 2,


Problem2
Consider the plane truss shown in.
Given E= 210GPa and A=0.005m^2,
Determine:
1. The global stiffness matrix for the structure.
2. The horizontal and vertical displacements at nodes 2, 3, 4, and 5.
3. The horizontal and vertical reactions at nodes 1 and 6.

You might also like