Sie sind auf Seite 1von 55

H04M2a Finite Elements, part 1

Introductory seminar MATLAB

Jie Zhang, Hernan Garcia, Jan Van den Wyngaert


Geert Lombaert

Department of Civil Engineering, KU Leuven


2016-2017
Contents
1. MATLAB desktop

2. MATLAB calculator
Exercises
3. MATLAB visualisation
Exercises
4. MATLAB scripts / functions

5. MATLAB command structures


Exercises
1. MATLAB desktop
environment
MATLAB desktop
HELP

Editor

Workspace
Browse for
Current
functions
Folder

Command
Window

History
MATLAB desktop
• Command window: interactive input via command line >>
• Current folder: overview of files in current working directory.
• Workspace: content of workspace (can be modified using the
array editor).
• Command history: overview of recently used commands.

• Help: (excellent) help.


• Editor: edit .m-files. Access by opening a .m-file or via New
Script icon.
HELP
• help + command name: online help in Command Window
• helpwin + command name: online help in Help Window
• doc + command name: online documentation
• lookfor + search string: look for search string in Matlab path

Use the demos in the help files!


HELP
HELP
>> help
HELP topics

matlab\general - General purpose commands.


matlab\ops - Operators and special characters.
matlab\lang - Programming language constructs.
matlab\elmat - Elementary matrices and matrix manipulation.
matlab\elfun - Elementary math functions.
matlab\specfun - Specialized math functions.
matlab\matfun - Matrix functions - numerical linear algebra.
matlab\datafun - Data analysis and Fourier transforms.
matlab\polyfun - Interpolation and polynomials.
matlab\funfun - Function functions and ODE solvers.
matlab\sparfun - Sparse matrices.
matlab\scribe - Annotation and Plot Editing.
matlab\graph2d - Two dimensional graphs.
matlab\graph3d - Three dimensional graphs.
matlab\specgraph - Specialized graphs.
matlab\graphics - Handle Graphics.
matlab\uitools - Graphical user interface tools.
matlab\strfun - Character strings.
matlab\imagesci - Image and scientific data input/output.
matlab\iofun - File input and output.
matlab\audiovideo - Audio and Video support.
matlab\timefun - Time and dates.
matlab\datatypes - Data types and structures.
....
Helpful commands and tips
• Ending a calculation or infinite loop: ctrl-c

• Stopping MATLAB: quit


exit

• Suppress output ; after command

• Run command: F9
• Run m-file: F5
Useful commands
• List of variables in the workspace: who

• Like who, but more info on size: whos

• Clear command window clc

• Clear variables from workspace clear


clear
clear name1 name2 name3 ...
• Clear command window and variables cl
MATLAB environment
• MATLAB interpreter
o Typed commands are executed immediately
o Variables are stored in memory when first used

• Variables created in the Command Window are stored in


the Base Workspace
o Values of variables can change
o Selected variables can be cleared

• MATLAB Path: list of search directories


o Basic path set (directories)
o Can be expanded (File/Set Path…)
MATLAB environment
MATLAB Command Window:
• Command
– load mydata (saved workspace in mydata.mat)
– whos

• Assignment statement
– 1 variable on left side of assignment ( >> A = ...)
– The variable type is automatically determined/adapted
(attention: easy but can cause problems!)
– Example: >> A = width*length;
>> B = 267;

• Variable names
– Up to 31 characters (letters, numbers and _ )
– Case sensitive (A_1 ≠ a_1)
Summary
• MATLAB uses basic Windows logic

• Make optimal use of HELP-tools

• Make use of demos!


2. MATLAB calculator
advanced computing
MATLAB calculator
• History of calculations is stored
o Defined variables can be used
o Previous commands can be called using ↑ and ↓

• Type the beginning of a command:


o ↑ : repeat a previous command with same beginning
o tab: overview of possible commands

• Copy/Paste to other files


• Fast and easy graphics
• Powerful data analysis
Built-in functions
• MATLAB has a large number of built-in functions

• Elementary MATLAB functions (help elfun)


o Trigonometric functions
o Exponential functions
o Complex functions
o Rounding and remainder

• Specialized MATLAB functions (help specfun)


o Specialized math functions
o Number theoretic functions
o Coordinate transforms
MATLAB arrays
• Fundamental data structure of MATLAB: array
o 1D array = vector
o 2D array = matrix

• MATLAB computes with matrices and stores matrix sizes

• Fundamental operators are programmed to work optimally


with matrices

• Make use of the built-in MATLAB functions!


Building arrays
Option 1
• Specify each element separately using []
• Separations between elements:
- Column separation: blanc or ,
- Row separation: ;
• Example: >> a = [1 2 3]
a =
1 2 3
>> b = [11, 2, 3]
b =
11 2 3
>> c = [1;2;3]
c =
1
2
3
Building arrays
Option 1
One of the most useful operators in MATLAB is :
• j:k - builds[j,j+1,…,k]
- is empty when j>k

• j:i:k - builds[j,j+i,j+2i,…,k]
- is empty when i>0 and j>k or
when i<0 and j<k
• Example: >> d = [1:5]
d =
1 2 3 4 5
>> e = [1:2:10]
d =
1 3 5 7 9
Building arrays
Option 2
• Specify each element explicitly:
a(1) = 3;
You can also select a specific matrix element (of an already defined
matrix) this way, e.g. a_23 = a(2,3);

Option 3
• Use a built-in command such as linspace or logspace
a = linspace(0,4,20);

Option 4
• Use built-in standard arrays
eye, zeros, ones,…
Matrices: elementary functions
• diag: diagonal matrix with vector elements on diagonal
• eye: unit matrix
• linspace: linearly increasing array
• logspace: logarithmically increasing array
• ones: matrix with constant values
• zeros: zero matrix
• rand: random matrix
• sparse: take sparsity of matrix into account

→ start with help elmat


Matrices: dimensions
• Determine dimensions of a matrix/vector: size

• Determine length (largest dimension): length

• Example:
size(A,1) yields the number of rows of matrix A
size(A,2) yields the number of columns of matrix A
Matrices: operations
array summation a+b

array difference a-b

array product a.*b → element-wise: a(i,j)*b(i,j)


a*b → matrix product

array division a./b → element-wise a(i,j)/b(i,j)


a.\b → element-wise b(i,j)/a(i,j)
a/b → a * inv(b)
a\b → inv(a)*b

array exponent a.^b → element-wise a(i,j)^b(i,j)


Solving a system of equations
• Equations: 5x = 3y – 2z + 10
8y + 4z = 3x +20
2x + 4y – 9z = 9
• Reformulate as standard matrix format A x = b
• Determine x

• MATLAB:
>> A = [ 5 -3 2;
-3 8 4;
2 4 -9];
>> b = [10; 20; 9];
>> x = A \ b
Summary
• The array is the basic MATLAB unit and can be built in
several ways.
• MATLAB allows for all types of computations and
operations.
• Use the HELP-tool!
• Other data types are possible: look up ‘data structures’
using the help-tool for further details.
Exercises
• Exercise 1 – Building a matrix

• Exercise 2 – Determine matrix dimensions


Select matrix elements

• Exercise 3 – Solving a system of equations

• Exercise 4 – Matrix operations


• Exercise 5 – Using help functions

• Exercise 6 – Using help functions


3. MATLAB visualisation
Visualisation: plottools
• MATLAB provides several different ways to visualize data. The
most popular procedures include:
1. Built-in MATLAB commands
2. MATLAB Handle Graphics (object-oriented) procedures can alter the
properties of each graphical object. These handle graphics are also
used e.g. to create graphical user interfaces (GUIs) in MATLAB.

• Most standard 2D en 3D plots are built-in commands in


MATLAB
Start with: help graph2d → 2-dimensional graphs
help graph3d → 3-dimensional graphs
help specgraph → special graphs
2D plots
• Line plots plot
• Polar coordinates polar

• Surface area / fill


• Isolines contour / contourf
• Vector fields quiver

• Stair plot stairs


• Diagrams bar / pie
• Functions fplot / ezplot
2D plots: plot
• plot(Y)
→ plot columns of Y versus index

• plot(X1,Y1,...)
→ plot lines determined by vectors Xn versus Yn

• plot(X1,Y1,LineSpec,...)
→ plot lines determined by Xn,Yn,LineSpec triplets

• plot(...,'PropertyName',PropertyValue,..)
→ setting properties
2D plots: plot → line specs
• LineStyle:
- solid line (default)
-- dashed line
: dotted line
-. dash-dot line
none no line

• Marker (symbol)
+ o * . x s d ^ > < p h

• Color:
y m g r c b k w → help plot !!
2D plots: plot → basic commands
axis on/off → show / don’t show axes
grid on/off → show / don’t show grid

axis → keep current axes

axis([xmin, xmax, ymin, ymax])


→ set limit values for axes
text(x,y,‘string’)
→ show horizontal text starting at position (x,y)
line(x,y)
→ plot line specified by vectors x & y
2D plots: plot → examples
x = 0:0.05:5;
y = sin(x.^2);
plot(x,y);
title('Plot 1');

plot(x,y,'--rs',...
'LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
Multiple figures
• In same coordinate system: hold on
• In same window: subplot
• In new window: figure

• Calling different figure windows: figure(fig_no)

• Clear graph: clf / cla

• Close figure window(s): close(fig_no)


close all
Summary
• 2D/3D visualization is easily achieved in MATLAB

• Consult HELP to find out which built-in functions are


available:
help graph2d
help graph3d
help specgraph

• Interactive plot tool


Exercises
• Exercise 7 – Use 2D Plots
4. MATLAB scripts
and functions
.m-files
MATLAB programs
• MATLAB is an advanced calculator, which can be further
automated by programming

• Programming in MATLAB:
o Scripts: MATLAB commands are executed from a file
(file.m) in the workspace
o Functions: definition of program modules which produce
output(s) given certain input(s)

• Files can be constructed in any text editor, but easiest is to


use the built-in editor.
MATLAB editor

Click new script icon Open existing file

Type edit in the


command window
MATLAB file editor
debugger

keywords indents

tabs for other files


being edited
.m-files
• .m-file = ascii file, not a binary file
• Scripts
o Execute line by line, as a sequence of MATLAB commands
o Variables are created in the (user) workspace

• Functions
o First line starts with keyword function
o Code is built in memory when first called
o Variables are stored in the function workspace, not in the user
workspace
o Input arguments can be passed
o Output is possible but not necessary (function [])
.m-files: functions
• Name starts with a letter and ends in extension .m
• Maximum 31 characters

• The name of the function is defined on the first line of the m-file
• Should be the same as the name of the file!
• Structure function .m-file:
1. Function definition
2. H1-line
3. Help text
4. Body
5. Commentary
.m-files: functions
1. Function definition
A function is always defined after the keyword function
function y = gemiddelde(x)
function [x, y, z] = sphere(theta, phi, rho)
function printresult(x) of function [] = printresult(x)
2. H1 line
First line of help text where lookfor searches
3. Help text
Commented lines after H1, which are shown using the help function
4. Body
MATLAB code
5. Commentaar
Explanatory text after %
.m-files: functions
Example: traparea.m
Function definition
H1 line

function area = traparea(a,b,h)

% traparea(a,b,h) Computes the area of a trapezoid


% given the dimensions a, b and h, where a and
% Help text b are lengths of the parallel sides and
% h is the distance between these sides

% Compute the area, but suppress printing of the result


area = 0.5*(a+b)*h;

Body Commentary
How does a function function?
• A function can be called:
o From the command window
o From another .m-file

• Passing arguments
o Pass-by-value (intelligently): values that are not adapted are
passed as reference
function area = traparea(a,b,h)
output input

o Every .m-file function has its own memory space:


• Separate memory space from the global workspace
• Variables in function workspace are cleared after function call
Summary
• User-defined functionality in .m-files
→ save in current directory, or in search path

• Script-files vs. functions


o Functions have local variables
o Scripts act in the global workspace
5. MATLAB
command structures
Command structures
Classical control constructions are available in MATLAB:

if else elseif

switch case

while

for
Logical expressions
• Logical and conditional expressions:
o Comparative operators: < <= > >= == ~=
o Boolean operators: & (and) | (or) ~ (not)

• Result: 1 ↔ condition is TRUE


0 ↔ condition is FALSE

Example: >> a = 1;
>> b = 2;
>> disp(a>b)
0

• Evaluation is element-wise for arrays:


Example: >> x = [ 1 2 3 4 5 ];
>> y = [ 0 4 3 6 2 ];
>> disp(x<y)
0 1 0 1 0

• Use logical expression to select array elements:


Example: >> disp(x(x<y))
2 4
if statement
• If-statements are only executed when condition_x is true
• Format:
if condition if condition_1
statements statements
else elseif condition_2
statements statements
end else
statements
end

• When expressions with logical arrays are used, the expression


is only true if ALL elements are non-zero:
if (X>Y)
disp(‘all elements of X are larger than Y’)
end
switch statement
• A block of code is executed depending on the result of the
evaluation of the condition

• Format: • Example:
switch(switchcondition) x=1;
case case_exp_1 switch x
statements case 0
case case_exp_2 disp(‘x equals 0’)
statements case 1
… disp(‘x equals 1’)
otherwise end
statements
end >> x equals 1
while statement
• while is an extension of the if statement:
o A repetitive action is added
o The statements are executed while the condition is true (i.e. ≠ 0)

• Format: while condition


statements
end

• break can be used to get out of a loop


Example: while(1)
req = input(‘provide number or q to stop:’,’s’);
if (req == ‘q’)
break
end
disp(eval(req));
end

• Beware of infinite loops! (type ctrl-c in the command window


to terminate the program)
for statement
• for is analoguous to while statement:
usefel when it is known in advance how many times a set of statements
needs to be repeated.

• Format: for index-start:increment:end


statements
end

• for-loop can also use an array as indices:


for index = [1 2 3 5 7 11 13 17 19 23]

• break can also be used


Programming style
Basic guidelines:
• Follow the required specifications
• Comment your code
o Provide user documentation (help text)
o Explain used variables, used methods and functions
o Use clear language, no literature or subtleties
• Use indentations and spaces for clarity
• Generalize as much as possible
→ don’t copy-paste code, but re-use code by using
generalized functions!
Exercises
• Exercise 8 – Use functions and develop programming style

• Exercise 9 – Apply functions in a script

Das könnte Ihnen auch gefallen