introduction to matlab class 3
DESCRIPTION
Introduction To Matlab Class 3. Instructors: Hristiyan (Chris) Kourtev and Xiaotao Su, PhD Double click the matlab icon When prompted click “Skip”. Variables. Integersm = 5;% = [5] Doubles (Floating pt) n = 7.382; Character stringsc1 = ‘beep’ ; % = [‘b’, ‘e’, ‘e’, ‘p’] c2 = ‘4’; - PowerPoint PPT PresentationTRANSCRIPT
Introduction To MatlabClass 3
Instructors: Hristiyan (Chris) Kourtevand Xiaotao Su, PhD
Double click the matlab iconWhen prompted click “Skip”
Optional Presentation Title
Unit Name
Variables
• Integers m = 5; % = [5]• Doubles (Floating pt) n = 7.382;• Character strings c1 = ‘beep’ ; % = [‘b’, ‘e’, ‘e’, ‘p’]
c2 = ‘4’;• Arrays of numbers arr1 = [4, 5, 8, m];
arr2 = [m, n, 5.6, 0];• Arrays of strings str1 = [c1; ‘blob’]; % same dimen.• Concatenating arrays of numbers arr3 = [arr1, arr2];• Concatenating strings str2 = [c1,c2];• Matrices mat1 = [4, 5; 6, 7];
mat2 = [arr1; arr2]; % same dimen.• Cell Arrays (later on)
Optional Presentation Title
Unit Name
Accuracy of Displayed results
• Usually numerical values are rounded to 4 digits after the decimal
• Use “format long” and “format short” to display actual and short values respectively
>> d = 9.8479847498749847984d = 9.8480>> format long >> dd = 9.847984749874986
Optional Presentation Title
Unit Name
Boolean Expressions
• Boolean operands
• Boolean expressions either return 1 for true e.g. 5 == 5 or 0 for false e.g. 5 > 9
• Put expressions in parentheses so they get evaluated firste.g. 0 || (4<5)
== ~= > >= < <= && ||equals not
equalgreater than
greater than or equal to
less than
greater than or equal to
and or
Optional Presentation Title
Unit Name
Loops (for and while)
• For loop
for index = from:to% do something
end
• While loop
while(condition)% do something% change something that affects value of “condition”
end
Optional Presentation Title
Unit Name
Loops (for and while) -- examples
max_loops = 5;for index = 1:max_loops
disp(index);end
counter = 1;while(counter < max_loops)
disp(counter);counter = counter + 1;
end
%nested loop example
for k = 1:max_loops
disp(‘k1’);
for m = 1:3
disp(‘m’);
end
disp(‘k2’);
end
% outputs:
% k1 m m m k2 k1 m m m k2 k1 mmm k2 k1 m m m k2 k1
mmm k2
Optional Presentation Title
Unit Name
The “do-while” loop
• General syntax in most languages (does NOT exist in Matlab):do {
//run some code} while (condition)
• How to do it in matlab:while(1) % loop forever
% run some code here% check conditionif (condition)break; % get out of the loopend
end
Optional Presentation Title
Unit Name
Commonly used functions
• rand - generates a random decimal number between 0 and 1e.g. 0.3456 or 0.9993 or 0.0013 etc
• ceil(num) – returns the next integer bigger than the inpute.g. ceil(5.56) 6 or ceil(2.1) 3 or ceil(6) 6
• floor(num) – returns the next integer, smaller than the inpute.g. floor(0.9) 0 or floor(-0.1) -1
• To generate a random number between 0 & 20: ceil(rand*20)
Optional Presentation Title
Unit Name
Commonly used functions -- continued
m = [1, 2, 3, 4]; n = [1, 2, 3, 4; 5, 6, 7, 8]; k = [9; 8; 0];
• length(mat) – returns the length of a vector or a matrixe.g. length(m) 4, length(n) 4, lenth(k) 3
• size(mat,dim) – returns all the dimensions of a matrix/vectore.g. size(m) [1, 4], size(n) [2, 4],
size(k) [3, 1], size (n, 2) 4
Optional Presentation Title
Unit Name
Multiple Input/Output Functions
• Functions can have more than one input and more than one output
e.g. s = size(mat, dim);
• Storing returned values in 2 or more separate variables
e.g. [x, y] = size(mat);
• Storing returned values in a vector/cell array
e.g. vals = size(mat);
Optional Presentation Title
Unit Name
Collecting User Input & Using it
• Take input from keyboardnum1=input('what is the first number?');
• Validation checks: - isstr(var)- isnum(var)
• Converting from strings to numbers and back- num2str(var)- str2num(var)
Optional Presentation Title
Unit Name
Calling scripts within scripts
• This is done to modularize code• Modular code is useful because you can
– reuse the same piece of code in many different programs– have the same piece of code called many times in one program– Only have to debug that piece of code once and then be able to rely on
it to work the same way all the time.
Optional Presentation Title
Unit Name
calling scripts
% my_prog.m
j = 4;
double_j
if(j<7)
double_j
else
half_j
end
disp(j)
% double_j.m
% doubles the value of j
j = j*2;
% half_j.m
% cuts j in half
j = j/2;
Optional Presentation Title
Unit Name
calling scripts
% my_prog.m
j = 4;
double_j
if(j<7)
double_j
else
half_j
end
disp(j)
% double_j.m
% doubles the value of j
j = j*2;
% half_j.m
% cuts j in half
j = j/2;
Optional Presentation Title
Unit Name
Added benefit
% my_prog.m
j = 4;
double_j
if(j<7)
double_j
else
half_j
end
disp(j)
If double_j and half_j were much more
complicated programs the benefit to seperating
them out into separate scripts makes our code
•Shorter
•Simpler to read
•Less likely to have bugs
You can also have your program perform
largely different behaviors based upon
different conditions.
Optional Presentation Title
Unit Name
%draw_stuff.m
clear all;
screen_setup
while( …)
…
screen(window, ‘FillRect’ …
flip
end
clear screen
%screen_setup
---Determine Operating System---
if(oldmac|win)
Set up screen variables
for old mac and windows
else
Set up screen for OS X
end
if(osx ==1)
Screen(window,'Flip');
else
Screen('CopyWindow', window, window_ptr);
Screen('CopyWindow', blank, window);
Screen(window_ptr, 'WaitBlanking');
end
making programs for all versions of psychtoolbox
Optional Presentation Title
Unit Name
Functions
• Functions are similar to scripts in that– they are separate from your main body of code– used to perform one coherent task– make your code neater
• Differences– You pass it specific variable(s) and it returns specific variables(s)– The variables within it are not accessible outside the function– The variables outside the function are not accessible inside the function
Optional Presentation Title
Unit Name
%my_prog.m
f = 4;
k = double_me(f);
i = 6;
f = double_me(k);
disp(f);
disp(i);
function d_val = double_me(i)
%double_me.m
%doubles any value passed to it
d_val = i*2;
Example of functions
Optional Presentation Title
Unit Name
%my_prog.m
f = 4;
k = double_me(f);
i = 6;
f = double_me(k);
disp(f);
disp(i);
function d_val = double_me(i)
%double_me.m
%doubles any value passed to it
d_val = i*2;
Example of functions
•Notice, i was set to 6 in my_prog, and i was used in double_me,
but the two references didn’t effect eachother.
•Also each call to a function creates a separate set of variable
references for that call.
my_prog’s variables
f = 4 then 16
k = 8
i = 6
double_me*’s variables
i = 4
d_val = 8
double_me**’s
variables
i = 8
d_val = 16
Optional Presentation Title
Unit Name
%my_prog2.m
f = 9;
[a, b] = double_times(f, 4);
c = double_times(f, 4);
disp(a);
disp(b);
disp(c);
function [d_val, t_val] = double_times(i, fact)
%double_times.m
%doubles any value passed to it and multiplies
d_val = i*2;
t_val = i*fact;
Multiple inputs/outputs
Optional Presentation Title
Unit Name
Small Pieces
• Starting with matlab version 7.0 you can execute small chunks of code
• This is called cells (nothing to do with cell arrays)• %% mark off the beginning and end of cell region• Cell regions are seen as yellow • Pressing ctrl/cmd + return causes the workspace to execute the
command in the active cell
If you do not see a yellow region, in the menu
bar select Cell->Enable Cell Mode
Optional Presentation Title
Unit Name
For loops using different increments
for i=1:10
disp(i);
end
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for i=1:2:10
disp(i);
end
1, 3, 5, 7, 9
for i=2:2:10
disp(i);
end
2, 4, 6, 8, 10 for i=10:-2:1
disp(i);
end
10, 8, 6, 4, 2
for i=10:-1:1
disp(i);
end
10, 9, 8,7,6,5,4,3,2,1
Optional Presentation Title
Unit Name
Task 1
• create a function that will take any stringand spell it backwards
• reverse_string(‘stressed’)returns ‘desserts’
for i=1:10
disp(i);
end
The length of a string is
length(str_var)
Tips:
function d_val = double_me(i)
Optional Presentation Title
Unit Name
Using images in experiments• Images are stored in matlab as Width x Height x 3 matrix
RG
B
x
y
Optional Presentation Title
Unit Name
file -> matrix and drawing it on the screen
• img = imread(‘winter.jpg’, ‘jpg’);
• To display an image use the ‘image’ command:image(img);
Optional Presentation Title
Unit Name
Making sounds
• A sound is a 2 x N matrix where N is the number of bits that make up the sound file and the two channels are for left and right
Optional Presentation Title
Unit Name
Making sounds
• [sound, samplerate, samplesize] = wavread(‘chord.wav’);
wavplay(sound, samplerate); % on PCsound(sound, samplerate); % if you have a Mac
Tip:
To make your own wav files I recommend
using an application called audacity
http://audacity.sourceforge.net/