User Tools

Site Tools


matlab:introduction_to_matlab

View page as slide show

Introduction to MATLAB

Mithat Konar
2017-04-23

What is it?

  • A freaking huge, feature filled graphing calculator
  • Comprehensive
  • Expensive

Alternatives

    • FOSS (GPL)
    • Mostly syntax compatible
    • 3rd party SaaS available
    • FOSS (GPL compatible CeCILL license)
    • Similar idea, not as compatible
    • FOSS (MIT-like)
    • Python based, very different
    • Increasingly popular

Two Modes

  • Interactive
    • Interact using a command line interface.
  • Scripted
    • Run scripts stored in files.
  • Same syntax in both

Variables

  • MATLAB has only one numeric type.
  • Strings are OK too.
    • Use single quotes.
    • For a literal single quote in a string, use two single quotes.
  • Lots of other types.
  • Ending with a semicolon suppresses output to console.
a = 3.14159
b = a + 5
c = sin(a);
foo = 'How''s it?'

Comments

  • Use a percent sign.
% like this
a = 99; % this works too
 
%{
foo = 'This is a';
baz = 'multiple line comment';
%}

Row vectors

  • One dimensional horizontal array.
a = [5 4 2 1]
b = 1 : 10         % [1, 2, ... , 10]
t = 0 : 0.1 : 1    % 0 to 1 in 0.1 steps
x = 0 : 0.1 : 2*pi % 0 to 2π in 0.1 steps

Vector functions

% x is a row vector
x = 0 : 0.1 : 2*pi
 
% compute sin(x) from 0 to 2π
y = sin(x)
 
% how big is a variable?
size(y)
 
% many, many more ...

2D Plotting

% plot row vector (index is abscissa)
plot(y)
 
% plot y vs. x (lengths must match)
plot(x, y) 
  • x, y variable names are not special.
  • Indexing starts at 1!

Complex numbers

x = 0.3 + 0.4i;

Higher dimensions

% separate matrix rows with ';'
a = [1 2 3; 4 5 6; 7 8 9];
c = [9 8 7; 6 5 4; 3 2 1];

Matrix operations

% matrix multiplication
r = a * b;
 
% elementwise multiplication
r = a .* b;
 
% elementwise division
r = a ./ b;

Matrix inverse and transpose

r = inv(a); % inverse
r = a';     % transpose

Indexing

  • Starts at one.
% individual element (row, col)
a(3, 2);
 
% submatrix (row range, col range)
bigMatrix(1:3, 10:end);
 
% set values of submatrix, all cols
bigMatrix(1:3, :) = -1;

3D plots

t = 0 : 0.1 : 1;
data = sin(2*pi*t);
z = data' * data;
 
% create a surface plot
surf(z);

What variables?

% display info about variables in current workspace:
whos

Clearing

% clear the screen:
clc
 
% clear (delete) variables:
clear varname1 varname2
 
% clear all variables:
clear

Help!

help what-you-want-help-with

Some useful functions

  • sqrt(x): square root
  • mod(a, b): modulus after division
  • ones(m, n), zeros(m, n): matrix of all ones or zeros
  • rand(m, n): matrix of random numbers
  • linspace(x1, x2, n): n linear points between x1 and x2
    • n defaults to 100
  • Heaps more: don't reinvent the wheel!

MATLAB scripts

  • Scripts containing MATLAB code can be stored as filename.m.
  • Run by invoking filename.
plot_sinc.m
% Plot sin(x)/x for x = -4*pi to 4*pi.
 
x = linspace(-4*pi, 4*pi, 1000);
y = sin(x) ./ x;
 
plot(x, y); % will skip NaN points

Console output

  • With disp().
a = 'hello';
disp(a);
disp([a ' world']); % [] is one way to concatenate strings
c = 42;
disp(c);
disp(['The answer: ' num2str(c)]); % conversion required

Console input

  • With input()
prompt = 'What is the frequency? ';
x = input(prompt);        % evaluates input
ans = input(prompt, 's'); % doesn't evaluate, 
                          % can get string.

Control structures

if, if/else

if x > y
  disp('Ponies!');
elseif x == y
  disp('Skittles!');
  disp('... don''t eat them all at once.');
else
  disp('Rainbows!');
end
  • Use commas to do everything on one line.
  • Commas not needed for statements ending with a semicolon:
if x > y, disp('Ponies!'); else disp('Rainbows!'); end

switch

switch switch_expr
  case case_expr, 
	statement, ..., statement
  case {case_expr1, case_expr2, case_expr3,...}
	statement, ..., statement
  ...
  otherwise, 
	statement, ..., statement
end
  • switch_expr doesn't need to be a number
  • case can match multiple values
  • No “break” is needed.

while

while n < 10
  y = y * n;
  n = n + 1;
end

Una línea:

while n < 10,  y = y * n;  n = n + 1; end

for

for n = 0 : 0.5 : 2
  disp(n);
end

一条线

for n = 0 : 0.5 : 2, disp(n); end

Nesting control structures

  • No problem.

Relational operators

  • a < b, lt(a, b)
  • a > b, gt(a, b)
  • a <= b, le(a, b)
  • a >= b, ge(a, b)
  • a == b, eq(a, b)
  • a ~= b, ne(a, b)

Logical operators

  • a && b: short-circuit logical AND (scalars only)
  • a || b: short-circuit logical OR (scalars only)
  • a & b, and(a, b): element-wise logical AND (scalars or vectors)
  • a | b, or(a, b): element-wise logical OR (scalars or vectors)
  • ~a , not(a): logical NOT
  • xor(a, b): logical EXCLUSIVE OR

More logical operators

  • any(a): true if any element of vector is nonzero
  • all(a): true if all elements of vector are nonzero

User functions

  • Functions can be defined in a .m file with a main function.
    • Several functions in one file.
    • Functions aren't shared.
  • Functions can be defined in files that also end in .m
    • One function per file.
    • File name must match function name.
    • Functions can be called by any other .m file or interactively.

With "main" function

  • Minimum syntax:
my_script.m
function main
  area1 = traparea(1, 2, 3);
  disp(area1);
end
 
function area = traparea(a, b, h)
  area = 0.5 * (a + b) * h;
end

Stand alone function

  • Minimum syntax:1)
traparea.m
function area = traparea(a, b, h)
  area = 0.5 * (a + b) * h;
end
calc_trap_area.m
% Uses traparea function defined in traparea.m
area1 = traparea(1, 2, 3);
disp(area1);

Documenting functions

  • First comment block after first line is used to document functions.
  • What user sees when she types help function-name.
    • Only with single-function m-files.
traparea.m
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 b
%                     are the lengths of the parallel sides and
%                     h is the distance between these sides.
 
area = 0.5 * (a + b) * h;
end

Which path?

  • userpath: list the directories where MATLAB looks for m-files.
  • addpath: add additional directories where MATLAB looks for m-files.
  • savepath: make changes permanent.
  • pathtool: launch a GUI to manage paths.

MATLAB's IDE

1)
Recktenwald, Gerald. “MATLAB Functions – Basic Features.” MATLAB Functions – Basic Features. Accessed April 30, 2016. http://web.cecs.pdx.edu/~gerry/MATLAB/programming/basics.html.
All examples in in the “User functions” section are from Recktenwald.
matlab/introduction_to_matlab.txt · Last modified: 2017/04/24 04:46 by mithat