Download presentation
Presentation is loading. Please wait.
Published byTyler Park Modified over 8 years ago
1
Introduction to Matlab PHY 329 8 September 2016
2
Why Matlab? No need to compile code Huge amount of built-in functions Highly optimized and fast, in general Environment combines programs/functions and an interpreter M-files can also be compiled for more speed Extensive documentation Large user base and robust online community are other resources Ease of use
3
The Matlab Environment Editor: for writing scripts and m-files Workspace: variables and objects File explorer Command window: for running functions, scripts, defining variables, and calculating
4
Defining variables - scalars Every variable in Matlab is a matrix CASE SENSITIVE Definition will be printed unless suppressed with a ; at the end of the line Scalar: >> x = 5; c = 3e8; Complex number: >> z = 3 + 9*i; or >> z = 3 + 9*j; Predefined variables: pi, ans, eps, Inf
5
Defining variables - scalars Format output using the format type command Possible types:
6
Defining Variables – vectors and matrices Row vector: r = [1 3 6 0 4], or r = [1, 3, 6, 0, 4] Column vector: c = [2; 5; 6; 3] or c = [2 5 6 3]’ Transpose operator: ’ Matrices: M = [3 4 5; 6 5 3; 9 0 7], or M = [[3 6 9]’ [4 5 0]’ [5 3 7]’] Elements: M(3,2) = 0, r(4) = 0 ones(m,n), zeros(m,n), eye(m,n), rand(m, n)
7
The colon operator Defining vectors a = start:interval:end a = 3:10 = [3 4 5 6 7 8 9 10] a = 4:.2:5 = [4 4.2 4.4 4.6 4.8 5] Negative increments also allowed Element selection a(3:6) = [5 6 7 8] Row/column selection from a matrix M(2,:) = second row, M(:,3) = third column linspace() and logspace() operators
8
Strings and multi-line entry Strings Single, not double, quotes s = ‘the five thousand pound man’ Concatenation: cat = [s ‘by rahsaan roland kirk’] = ‘the five thousand pound man by rahsaan roland kirk’ Multiline entry >> u = [2 4 5 2 4 … 9 0 6 5]
9
Mathematical operators Work on numbers and variables, including vectors and matrices Row vector r, column vector c r *c = scalar, c*r = matrix (outer product) Matrix/vector dimensions must make sense Left division is crazy: A x = b -> x = b \ A Element-by-element operations: add a dot before the operator
10
Built-in functions Basic info func(args) Described by the help, use help funcname Usually operate on matrices and vectors element-by-element Some have matrix versions, found by appending ‘m,’ ie sqrtm(M) Examples sin(x) log(x) sqrt(x) mean(v)
11
Plotting Array vs array For example, t = 1:30; v = 11:40; plot(t, v.^2, ‘p--m’) xlabel(‘t’) ylabel(‘v^2’) fplot() to plot functions plot3() for 3d plots hold on, then plot() again to plot multiple data sets subplot() for sub-figures Axes/titles rendered using TeX, you can specify LaTeX using 'Interpreter','Latex'
12
Using the help demo for tutorials and videos for new users help function_name for documentation about a specific function lookfor search_string to search the help Matlab Answers: https://www.mathworks.com/matlabcentral/answers/index https://www.mathworks.com/matlabcentral/answers/index
13
M-files – script files Two types of m-files: script files, and function files Script files Executed using run script_name Consist of a series of commands that would otherwise be typed into the command window Variables defined in script files persist in the workspace, that is, they are global
14
M-files – function files Function files Take arguments Do stuff (calculate, manipulate input) Return result(s) Like functions defined in normal programming languages Help comments printed in response to help funcname First line of help comments indexed for searching by lookfor Run by typing funcname(args) Variables are local
15
input() and disp() input(prompt_string) takes input from the user Useful for making interactive functions that take input from input() instead of as arguments disp(value) will display its argument to the command window Can take variables or constants Like the Python print() function
16
fprintf() Finer grained control over output Displays text and variables, controlled with format codes and control codes fprintf(‘text’, var1, …)
17
File I/O Saving Default behavior: save a.mat file that contains part or all of the workspace.mat files are binary, only readable by Matlab save filename var1 … varN ASCII files can be saved using the -- ascii option Useful for saving data or results save filename --ascii Loading Can load an entire workspace or select specific variables load filename var1 … varN Loaded files can be assigned to variables grades = load grades.txt
18
Control Structures – if statements if statements Execute when their condition is true Can be a single line for one statement if condition statement end And ( & ), Or ( | ), and Not ( ~ ) Order of operations: Not, And, Or If-else for two possibilities If-elseif-else for more possibilities
19
Control Structures – switch statement Like if-elseif-else, but it tests a single expression Tests expression and takes action depending on its value Optional otherwise case for input that doesn’t match any of the cases
20
Loops – for loop Repeats statements inside the loop a set number of times Uses colon notation Possible to use negative step sizes
21
Loops – while loop Run until some condition is met Careful not to make a condition that will never be met Ctrl-C to stop execution, if you find yourself in an infinite loop
22
Recursive functions Functions that call themselves Can implement some things much more cleanly For example, the factorial function here doesn’t require a loop Exercise: write an m-file to calculate the Ackermann function function f = factorial(n) % Calculate the factorial n! if n == 0 out = 1; else out = n*factorial(n – 1); end f = out;
23
Anonymous Functions Functions defined in the command window, not in an m- file Can include variables from the workspace Function doesn’t change if the variables do fhandle = @(arglist) expression
24
Functionals (aka function functions…) Written like normal functions, but one of the arguments is a function Use varargin to pass arguments to functions inside
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.