280 likes | 438 Views
How to Think through your program. Session 5, 4.12.2008 Christian Kaul. MATLAB for Cognitive Neuroscience. How to Think through your program. “How can I spend LESS time in front of MATLAB?” … the key to effective programming…. Effective programming principles: Language? Modelling
E N D
How to Think through your program Session 5, 4.12.2008 Christian Kaul MATLAB for Cognitive Neuroscience
How to Think through your program “How can I spend LESS time in front of MATLAB?” … the key to effective programming…
Effective programming principles: • Language? • Modelling • Readability • Reusability • Divide & Conquer • A few exemplary pieces of code
Effective programming principles: • Language?
Effective programming - LANGUAGE? • Why is it called a programming language? • Matlab is a very powerful programming language with which you can achieve nearly everything! • important to understand its grammar & using it • Important to constantly learn new vocabulary & grammar • Important to use your language understandable • … because leaning programming is just like learning a language.
Effective programming - LANGUAGE? • … so you must keep learning: • Grammar: statements can be coded in different ways - learn new stuff all the time • New Vocabulary: constantly check out help & the internet for newfunctions • Make yourself understood: keep it easy and explain things to yourself in comments.
Effective programming principles: • Language? • Modelling
Effective programming - MODELLING • Do you know what you want? --> The Modelling step! • Modeling = • Drawing a flowchart listing the steps we want to achieve. • Defining a model first makes it easier to break up a task into discrete, simple pieces. • We can then focus more easily on the smaller parts of a system and then understand the "big picture“.
MODELLING - Examples: Start Stim program Type in subject number Produce moving dots for backgroud, 100 frames Load main task images Start presentation Repeat 4 times, Record response Repeat again, Calculate mean over last 5 trials no Higher than alpha lower than alpha Go the next image Increase image contrast End of images? yes Calculate overall time, save result, end
Effective programming principles: • Language? • Modelling • Readability
Effective programming - READABILITY • Readability • brings clarity — ease of understanding. Understanding a program is the first step in either building or enhancing it. It makes it easy to document.
Effective programming - READABILITY • avoiding lists: • Many lists can be avoided. • Lists clutter your code and make it hard to read. • Therefore: • Consider the use of matrices & loops whenever you see a list. • Consider structs to group variables & information • If you really need a list have it in a separate file/function, it’s likely you can then reuse it in another script: setupValues = getSetupValues();
Effective programming - READABILITY • sounding variables, • Call your variables names that tell you what they stand for: Instead: I = j - mean(f1), have names like: MeanBaselineCorrectedValue = result - mean(baseline) • Define & assign your variables ONLY at the beginning of your script. • Never “hard code” numbers and values inside the main body of your script.
Effective programming - READABILITY • commenting, • Comment WHILE you write • -->It will take you twice the time one day after, four times the time one month later • Group your comments neatly away to a common indent, this way you avoid “cluttering” your code and ensure readability. • Have a short explanatory commented out section at the beginning of your script. Explain in simple terms what you code is doing there.
Effective programming principles: • Language? • Modelling • Readability • Reusability
Effective programming - REUSEABILITY • Reusability • After a system has been modeled to make it easy to understand, we tend to identify similarities or redundancy in the smaller steps involved.
Effective programming - REUSEABILITY Identify bits of your code that do stuff over and over again. Write a simple function with inputs & outputs How? Write a file ‘fnname.m’, starting with function [output1,… N] = fnname(input1,…N) Matlab will automatically recognize your function (as long as it’s on the matlab path)
Effective programming - REUSEABILITY • control variables, • Define control variables at the beginning of your program (& comment them) • control variables help you to keep your script flexible and are a good tool to avoid hard-coding data in your code. • Give them sounding name
Effective programming - REUSEABILITY • loop structures, • Keep your loops small and readable • Whenever you find a line of code inside a loop that does not contain a variable used in that loop put it outside the loop immediately. • Use CTRL-i to automatically indent your script and your loops for better readability.
Effective programming principles: • Language? • Modelling • Readability • Reusability • Divide & Conquer
Effective programming - DIVIDE & CONQUER • Divide & Conquer, • Is the principle to break large tasks up into small sub-units to be able to compute / understand them. • Is achieved by deciding to put simple units of your code in separate functions. • Ideally, these functions can be reused
Effective programming principles: • Language? • Modelling • Readability • Reusability • Divide & Conquer • A few exemplary pieces of code
Variables at start, Sounding names Readability, Comments, Short & easy loops • Collecting & Saving data in your stimulus script • outputPath = 'c:\home\ckaul\'; • Subjectname = input('Please enter subject name: ','s'); • Subjectnum =input('Please enter subject run number: '); • Subjectnamerun =[subjectname, int2str(subjectnum)]; • Filename =[subjectnamerun, exp_behav_res.mat']; % data file name (one per trial) • NoOfTrials = 10; • if exist([ outputPath filename],'file') • error('Results file already exists!'); • end • For trial = 1:NoOfTrials • %stim presentation here • Datafilename = [datafilename int2str(trial) ‘.mat’]; • Eval([‘save ‘ datafilename 'data‘]); % save data(!) after EACH trial • End % trial • For trial = 1:NoOfTrials • Result(trial) = eval(['load ' datafilename int2str(trial) ‘.mat’]); • end • Final.result =Result; • Final.NoOfTrials = NoOfTrials; • … • Save([ outputPath filename],’final’); Different grammar, same function Using stucts to group data
Effective programming - EXAMPLES • Everybody knows the endless boredom of copying loads of files from one into the other directory for many subjects, runs, etc. • Why not have it done automatically! • Example: sorting raw fMRI data • File: sort_raw_fMRI_data.m
Prewritten functions often make life much easier: • Selecting many files with SPM-select • Many SPM functions require long long list of filenames as input. This can be very tedious to program. • The SPM-select function helps! • % define epi files in the run • epiDir = [origDir dataFolder]; • % select scans and assign to all_files • f = spm_select('List', epiDir, ['^' MAO5675'.*\.img$']); • % add folder name to filenames • fs = cellstr([repmat([epiDir '\'],size(f,1),1) f]);
Struggling with Errorbars? • Struggling to place your errorbars at the right point? • Instead of endless trial & error, search web for a better function:Barweb.m (http://www.mathworks.com/matlabcentral/fileexchange/10803)