Download presentation
Presentation is loading. Please wait.
1
Creating a script create new blank document
2
Editor options Docking and undocking tabs
3
COMMAND WINDOW versus EDITOR
4
Command window Commands are executed immediately when you press Return
Variables that are created appear in the Workspace Cannot define functions here
5
Editor Commands are not executed right away*. They will only be executed when you invoke the saved file from the Command Window. When you do that, everything in the file will be executed, in order. Variables created here will not appear in the Workspace before executing You may define functions here * if you want one or more lines from a file in the Editor to be executed immediately, you can do that: Highlight the part you want to execute Text menu -> Evaluate selection…. or press Shift + F7 (on mac)
6
Writing scipts: M-Files
M-files are text files containing Matlab code (i.e. not just data) and are created/edited using Matlab Editor The files are saved under the name *.m ( rather than *.mat) NB A key problem that new users often face is that the directory in which the file was stored is not the current directory in Matlab. Check on this!!!!
7
Your first script Save script as “myFirst.m” % My first script x = 5;
z = x + y Save script as “myFirst.m” >> myFirst z = 11
8
Your first script Save script as “myFirst.m” EDITOR COMMAND WINDOW
% My first script x = 5; y = 6; z = x + y EDITOR Save script as “myFirst.m” >> myFirst z = 11 COMMAND WINDOW
9
Comments Comments start with % and appear in green in the editor
Can appear on their own line, or on a line with code provided they are after the semicolon Hint: you may use comments to temporarily disable lines of code
10
M-files example (script/module)
Write the days2go script: date_now=clock; next_year=date_now(1)+1; date_eoy=[next_year ]; diff_time=etime(date_eoy,date_now); days=floor(diff_time/(60*60*24)); disp(sprintf(‘Days between now and end of year: %d’,days));
11
M-files example (script/module)
% write a program to display the number of whole days between now and the end of year clear all; close all; % remove old variables & close old graphic windows date_now=clock; % get current date and time next_year=date_now(1)+1; % calculate next year date_eoy=[next_year ]; % date on Jan 1st midnight (end of year) diff_time=etime(date_eoy,date_now); % difference in sec between eoy/now days=floor(diff_time/(60*60*24)); % convert to days and round disp(sprintf(‘Days between now and end of year: %d’,days)); % print out result >> days2go
12
What is a function? A function is a self-contained piece of code that accomplishes a specific function It may take in certain variables (inputs), do something to them and return results (outputs) It has an INPUT, an OUTPUT and a name It has it’s own, local (vs. global) variables
13
Function declarations
All functions must be declared, that is, introduced in the proper way. code folding result of the function name of the function parameters passed to the function OUT IN
14
Function declarations
Functions may return no variables: function printAName(name) %Not very exciting. Just prints a name. fprintf(‘The name is: %s\n’,name); Or several: function [avg,biggest,smallest] = getSomeStats(x) %Return some statistics on vector x avg = mean(x); biggest= max(x); smallest = min(x);
15
Scripts and Functions Example Place the following code into a ‘.m’ file, give it the name mymultiply.m and call it from the command line: function r = mymultiply(a, b) % function definition r = a*b; % the actual code that does something return % not really needed, but good practice
16
Scripts and Functions Q: What is the difference between a Matlab script and a Matlab function ? A: Variables in Matlab scripts are held in the main Workspace, and are always visible to you from the Workspace. Variables defined and used in functions are “private”, i.e. in context only within the “scope” of that function (i.e. in the function, as it is being executed). Commands in the Workspace cannot see variables in the function, and vice versa. You can think of a function as having its own private Workspace.
17
Function variables are private
function private(x) x=1; y=2; disp(sprintf(‘x = %d’, x)) disp(sprintf(‘y = %d’, y)) return >> clear all >> x=0 >> private(x) >> x >> y
18
Scripts and Functions Q: So, if scripts and functions can’t see each others’ variables, what is the point ? A: Privacy of functions guarantees that functions and scripts can’t accidentally modify variables in each other (very useful to avoid bugs in complex programs!) Q: How can we access variables used by functions, and how can we make use of functions ? A: By passing arguments in and out of the functions; this can be done either from the main command line, or from other functions, without limit.
19
Global Variables If you really want more than one function to share a single copy of a variable, you can declare the variable as global in all functions that require access. Do the same thing at the command line if you want the main Workspace to access the variable. function r = mymultiply(a, b) global c; r = a*b + c; return At the Workspace command prompt, you could enter c = 34 (for example), then call mymultiply with the a and b arguments that you wish to pass. From experience, I avoid the use of global variables – because they have to be declared in every function that uses them, you are better off passing the variable into the function anyway. Top Tip: If the number of arguments you are passing into a function, or extracting at the output is getting very large, consider placing the arguments into the fields of a structure.
20
Coding style Your code needs to be readable by other humans
Never trust yourself to remember anything - just because something appears obvious now does not mean it will in the future, or to someone else. Use comments to explain what you are doing in English. In a collaborative laboratory setting your code is not just for you: you need to write to allow other people to update and change your code for their purposes you need to write your code to be as flexible as possible. this means we will expect the code to be transported to other machines, and other environments
21
Coding style ist= 10; sst= 4; r= [1,2]; ist = ist/fr; sst = sst/fr;
%set up standard presentation parameters instructionScreenTime = 10; %how long the instructions will stay on, in seconds stimulusScreenTime = 4; %how long the stimulus will stay on, in seconds acceptableResponses = [1,2]; %which responses buttons the subject may press %convert times from seconds into frames instructionScreenTime = instructionScreenTime/frameRate; stimulusScreenTime = stimulusScreenTime/frameRate;
22
Coding style Make your comments informative
%add two to the instruction screen time instructionScreenTime = instructionScreenTime + 2; %here we are adding two %add time to the instruction screen time to account for %the additional time needed by this subject population instructionScreenTime = instructionScreenTime + 2;
23
Coding style
24
Debugging Matlab includes a built-in debugging tool to help you diagnose errors in your code
25
NOTE: We are calling another function that we defined in the same file.
In a script, we can call functions that are: built-in Matlab functions defined within the same file in other files in the same folder in other files in folders that are in the PATH
26
Debugging proximal cause of error distal cause of error
>> debugDemo('SB02') Error using fprintf Function is not defined for 'cell' inputs. Error in debugDemo>printSomething (line 19) fprintf('This is your string: %s\n',stringToPrint); Error in debugDemo (line 11) printSomething(myConditions); proximal cause of error distal cause of error Links to the help file for that function Links to the line in the script where the problem occurred
27
BREAKPOINTS
28
Debugging >> debugDemo('SB02') 11 printSomething(myConditions); K>> >> debugDemo('SB02') This is the line where the script has paused (we set a breakpoint here). The line number is a link to the line in the editor. K>> prompt indicates that we are in debug mode Workspace shifts to showing all the variables in memory inside the function
29
GREEN ARROW SHOWS WHERE WE ARE PAUSED
30
Exercises Write a function called ‘average’ that returns both the mean & standard deviation of a list of numbers (use built-in functions sum and length). Write a function with no input values, a function with no output values and a function with neither Modify days2go.m such that it prints out the no of days from the beginning of the year and save the new M-file as daysgone.m (use comments). Convert the above script to a function that gives the days passed from your last birthday and the days remaining till your next birthday. Your birthday should be given to the function as a vector of length 2 (month, date). Debug debugDemo.m so that it works! Put comments after each command & get rid of commands which are not necessary..
31
Useful videos (Introduction to functions 6 min) (Function Input/Output 22 min) (Formal definition of functions 3 min) (Sub-functions 6 min) (Scope 6 min) (Advantages of functions 3 min) (Scripts 5 min)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.