Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia The goal for this tutorial is to make sure that you understand a few key concepts related to programming, and that you know the basics of the Matlab language. You don t need to turn anything in, just read through this document and execute the code that is provided. As you run through it, please ask an instructor or a classmate if anything doesn t make sense. Note that some of the commands that you will type will cause errors. Don t panic - this is intended for illustration purposes and to make you think about what happened. Exercise 1 Familiarize yourself with the GUI The first thing I would like you to do is to spend a little bit of time becoming acquainted with the Matlab interface, if you haven t before. Please locate the following items and make sure you know what they are for (there is nothing to answer, just check them off as you go: - The current directory dropdown menu - The view of the current directory contents - The workspace window - The command window - The command history window Next, let s have a look at the menus on the top of the interface. Find the following - The Set Path command (it s under the File menu) - The Editor command (it s under the Desktop menu) The next thing to note is that there is a lot of documentation available. The most frequent situation happens when you come across a command and you don t quite remember how it worked. In that case you type in the command line: help command_in_question For example: help plot 2 The Directory Structure and Matlab Matlab is a programming language and environment. As such, its job is to execute commands and manage information in the computer s memory and in the hard drive. When you are in matlab, whatever you do - execute commands, access data... etc, happens in a specific location in the file system (a.k.a. the directory tree). You can move up and down the directory tree using the Current Directory drop down menu. If you are working in the command window, the command "cd" (change directory) does the same thing to navigate the file system. The command "pwd" tells you where you are.
Try these on the command window and notice what happens (you don't need to write anything) cd C:\fMRI_Course\fMRI_lab\LabAssignments\ pwd Now do the same thing using the same thing from the user interface: use the drop down menu to go to the same directory. Please feel free to play around and move around the directory tree. 3 Matrices Matlab works with matrices (that s why it s called MATlab). It doesn t really know how to do anything else, so it treats almost everything as matrices or collections or matrices. All variables are considered to be matrices. As you will soon see, it even deals with text as matrices. Try a few basic commands. Type each of these lines in and observe what happens in both the command windows and the workspace window (again, no need to write anything, just check them off as you go) a = 1 a whos a Note what happens with the semicolon at the end (it suppresses the output to the screen you will want this when you have big matrices) a = 1; Let's make a matrix by hand: a = [1 2 3 ; 4 5 6 ; 7 8 9; 10 11 12] Now that we have a matrix, let's get a sense for how the data is stored and accessed within the matrix. Please pay close attention to the patterns and make a note of what each line gives you back. a(1) a(1,3) a(:,2) a(2,:) a(:) a(2:end, :) So now you see how you can access the different elements, rows, and columns of a matrix. Next, let s try doing things to matrices, i.e. changing their values, and doing operations on them: The "whos" command tells you the dimensions of the matrix. It's very useful when you have errors. a' a = [1:3:100] whos a Transposing a matrix: b = a' a = a' whos a (Warning: the quotes should always be single FORWARD quotes. The backward quotes are trouble!)
Remember, everything is a matrix in matlab so the operations are by default matrix operations!! Watch out for that. It takes a little getting used to. Let s play a little with matrix operations. Start out by making some matrices to operate on, then try some of basic operations and notice which ones work and which ones give you an error. a = [ 9 8 7; 3 2 1] b = [ 1 2 ; 4 5 ; 7 8 ] c = a * b c = a * b' c = 7 * a; So, as you can see, all the rules about multiplying matrices apply. On the other hand, this is how you do element by element multiplication and division (note that "*" is not the same as ".*" ) c = a.* b c = a.* b' Here are a few more practice exercises designed to get you used to matrices and their operations c = a * b; whos a b c = a' * b ; whos c c = a * b'; whos c Let s now look at how text is handled. If you want to set a variable to a string (a bunch of characters), you need to put them in quotes. If you don t, Matlab will think that these characters are some variable in your workspace. For example: a = 'some text... ' b = 'more text' (note, make sure they are single FORWARD quotes around the string too) c = [ a b] c = a + 10 c = a' *b Can you explain what happened with those strings? Here is a hint. Type the command double(a) Let s finish this exercise by removing the data from memory. Matlab can delete data from memory with the clear command. Type the following commands and note what happens. who clear b c whos clear all whos
4 Making graphs and displaying images with Matlab Matlab is extremely useful for displaying data. It can do all kinds of 2D, 3D plots, surface, contour plots, surface renderings, bar graphs you name it. Let's look at some basics by typing the following lines and noting what Matlab does in response. a = [0:0.1:3*pi]; figure plot(a) figure plot(sin(a)) figure plot(a, sin(a)) figure a = phantom; imagesc(a) colorbar colormap gray Note all the different menus you get on the figure itself. Now, find how to store the figure as a JPG image from the figure. When you want to get rid of a figure you use these close or if you want to get rid of all your figures, then you do this: close all 5. Storing and retrieving data from disk Matlab can read and write a variety of file formats, but right now we re just going to focus on a couple of them. Matlab is designed to work with data files that have a.mat extension. These are binary files that contain matrices. You can load a.mat file using the command load and you can save your matrices by using the command save. As an example, we have provided you with a couple of files to play with. Try this load( C:\fMRI_Course\fMRI_Lab\LabAssignments\Lab1_Matlab\data\SPM_fMRIDesMtx. mat ) you ll note that you specified the whole path to the file. But, you could also navigate (i.e., use the CD command) your way to the directory where the file lives and THEN do this: load('spm_fmridesmtx.mat') Now create your own.mat files. Try these and see what you get: save myvariables.mat (That saves everything in your workspace into a file. Check to see that you created the file with the ls command or just look with the file manager)
save somevariables.mat a b (That saves only the variables a and b) Those.mat files are in a special binary format and it takes some effort to decode outside of matlab, but If you want to create a quick text file to read in excel (or whatever) you can also do it with the save command, like this: save mytextfile.txt a -ascii You can open mytextfile.txt with notepad and look at its contents. You ll see it s just plain text. 6. Scripts and the path The concept of scripts is simple. They are nothing but a whole bunch of commands that have been copied to a text file, so that in the future you can execute them over and over without having to type them again individually. Instead of typing the commands one at a time, you can just execute the script and it will in turn execute all the lines in the order in which they are typed. There are two ways to execute a script: You can run a script from the command line or you can run it by opening up the Matlab editor and pressing the Execute button. Let s try an example of a script by opening the Matlab Editor window (you can do this from the command line by typing edit ). Now open a New blank.m file and copy a few commands from the above exercises into that file. When you are done, save the file in the C:\fMRI_Course\fMRI_Lab\LabAssignments\Lab1_Matlab directory with the name my_script_01.m Next, execute the script by typing in the command line my_script_01 VERY IMPORTANT NOTE: check your Current Directory. Is it C:\fMRI_Course\fMRI_Lab\LabAssignments\Lab1_Matlab? If it is not, Matlab will not know what to do and will give you an error. Why is that? The reason for this behavior is that Matlab is programmed so that when you type a command at the command line, it loads the command (script or function) into memory, translates it to machine language and THEN executes the instructions. Thus, the first thing that Matlab needs to know is where that command is saved. The first place it checks for the file containing the command/script/function is the current working directory. Matlab asks itself is there a my_script_01.m file at the current working directory?. If not, then it looks through a specific list of directories, called the path, and checks to see if the script (or function) is there. The last place that Matlab checks for a command is the native Matlab libraries that get loaded into memory when you start it up. This path is the list of directories where Matlab checks for programs and scripts. It is really
important and you should configure it so that Matlab knows where to find YOUR programs. Let s set your path now: Use the Set Path command (it s under the File menu). All you have to do is choose the directories you want to add to the path and hit the add folder button. You ll notice that the order matters. In other words, if there is a command that exists in two separate directories on the path, matlab will execute the first one that it finds. If you want to know the location of the script that Matlab will execute use the command which. For example: which my_script_01 Note: This sort of PATH concept is very common in all operating systems and computer languages It s likely that you already know about paths. It is very useful for two reasons. First, because it gives you control over what version of code gets executed and by whom. It would also be very impractical to have Matlab check the entire disk for programs every time it wants to run something. It would also be very impractical to have to write the whole location of the program every time you want to execute it. I just showed you how to set the path from the GUI. You can also do the same thing by typing this in the command line: addpath C:\fMRI_Course\fMRI_Lab\LabAssignments\Lab1_Matlab In fact, this second way of doing it is much more convenient and you are a lot less likely to make a mistake. So, let s do it that way from now on. 7. Functions In Matlab, functions work a lot like scripts: a nice text file with a bunch of commands in it that you call from the command window. BUT, there are some important features that make a function different from a script, though. The most important difference is that a script has access to all the variables that you have in the workspace and a function does not unless you specify that some variables go into the function. The workspace will have access to all the variables that you created in a script, but not the ones you created inside a function unless you specify that those specific variables be returned. In math, a function is some sort of manipulation to some numbers (input) that produces a result (an output). Programming functions works very much the same way. A function is a bunch of operations (commands) that work on a set of input variables and return a result. But that is where the similarity ends. Unlike Math functions, a Matlab function may do a bunch of stuff that has nothing to do with math, like moving files around, making figures etc. Another difference is that the number of inputs and outputs can be very flexible. The code of a function has a number of key features. The most important things to remember are: 1. The first line in a function has this format (below). This is usually called the declaration of the function. The first line of the file specifies the inputs and outputs of the function, like this: function result = function_name( input1, input2, etc.) 2. When a function is being executed, Matlab ignores all the variables previously in the workspace. It is as if a fresh new Matlab were started, and the only variables that matter are the ones INSIDE that function s code. So if you want to use any variables inside that function, you need to pass them as inputs to the function. Let s look at an example. First make your own function by typing (well copying and pasting) the following lines into a document in the Editor window: function y = add_noise( indata, noise_level )
% function y=add_noise( indata, noise_level ) % % This function will take whatever input data and foul it up by % adding gaussian noise to it. % % inputs: % indata: the data that will receive the noise % noise_level: a multiplicative function to determine how much noise to add % the_noise = noise_level * randn(size(indata)); y = indata + the_noise; plot(indata); hold on plot(y,'r') legend('original Data', 'Noisy Data'); hold off return First, spend some time staring at that code and try to figure out what each line does. Feel free to ask questions. Now call the function from the command line, as follows: t=[0:0.01:3*pi] x = sin(t); nd = add_noise(x, 0.2) 8. Structures A structure is a useful construct to group related data together in an organized way. For instance, we can group different data related to a single subject as a structure. This way when we need to do something with that subject, everything about that subject is easily accessible and you can do everything in one shot. Let s look at a toy example. Let s say that you are analyzing data from subjects, and each individual subject has a bunch of stuff you want to track, like their heart rate, their occupation, their hobbies whatever. This first line defines what things this subject structure should contain. It also puts default values into those elements: subject=struct('profession','professor','hobby','golf','heart_rate',200,'num_ students',15, 'EEG', randn(12,1000)) You could also make a structure by typing this directly: subject.profession='professor'; subject.hobby='golf'; subject.heart_rate= 200; subject.eeg = randn(12,1000); Now, when you want to access the data in the structure, you can access the individual data fields like this: subject.hobby If you have a bunch of subjects with the same sort of data, it may simplify things a lot if each subject is
treated as a structure. Matlab will let you create arrays of such subjects. This is a really nice way to keep your data grouped and organized. Something like this: subject(1).profession='professor'; subject(1).hobby='golf'; subject(1).heart_rate= 200; subject(1).eeg = randn(1000,3); subject(2).profession='accountant'; subject(2).hobby='dog sledding'; subject(2).heart_rate= 30; subject(2).eeg = randn(1000,3); etc Now that your data is grouped so nicely, then you could have a function that analyzes each subject s data. For example, let s say that you name your function perform_my_brilliant_analysis.m. You would pass all the info into the function like this: answer = perform_my_brilliant_analysis( subject(2) ) And the function would use the different fields in the structure to calculate well whatever it is that you want to calculate with the heart rate, EEG, and hobby.? If this seems odd now, in a couple of days, we ll see how this is also very useful to keep track of fmri images and image headers. 9. Loops We use computers to carry out calculations that we have to do over and over and over and over. This is particularly true in image data, where we do the same exact things to each of many thousands of pixels. This is one place where loops come in very handy. Loops exist in all programming languages. The basic idea is that there is a segment of the code that gets repeated as some sort of counter keeps incrementing (or decrementing). In Matlab, the loop is a bunch of commands sandwiched between a for command and an end command Example. Type this code into an editor window and execute it. Note what happens. % make a nice phantom to play with and display it im = phantom(100); subplot(211) imagesc(im) colormap gray % now make a second one with zeros in it im2 = zeros(size(im)); % at each pixel location (x,y) stick in the % weighted average of its neighbors: for x=2:99 for y=2:99 im2(x,y) = ( im(x, y) +... im(x-1, y-1) +...
end end im(x+1, y+1) +... im(x+1, y-1) +... im(x-1, y+1) ) /5; % display the result of the operations. This results in a blurring of % the image (or smoothing it, which sounds a lot better!) subplot(212) imagesc(im2) First, spend some time staring at that code and try to figure out what each line does. Feel free to ask questions. Can you identify the structure of the loop? What are the variables that are changing? What is staying the same? Can you modify the code so that you only blur the center of the image? 10. IF statements The last fundamental command that we ll cover is the IF statement. When the matlab interpreter finds the keyword if, it evaluates whatever comes next, and if it is true, then continues executing the next lines. If it s not true, though, Matlab skips the following lines until it finds an end statement. For example, copy and paste this into the editor and execute as a script: a = 1; if a==1 fprintf('\nyes!! a is equal to 1! Hooray!!! ') end fprintf('\nthis script is sadly over') Questions: Did you notice the use of == instead of =? Do you know why that is? The two mean different things. How about that fprintf statement? Do a help and read what it says about it. fprintf is really handy. If you can t figure it out on your own, please ask for help. Let s try one last example combining the IF statement with the FOR loop. Take this code and put it into a script. Execute it and note it s behavior. Can you figure out what the script does before executing it? % make a nice phantom to play with and display it im = phantom(100); % let's add a little noise to it im = im + 0.02*randn(size(im)); subplot(211) imagesc(im) colormap gray colorbar % now make a second one with zeros in it im2 = zeros(size(im)); % this is a very simple edge detector.
% at each pixel location (x,y) stick in the value of a % weighted average of its neighbors: for x=2:99 for y=2:99 noise = randn(1); % make the calculation only for those pixels that have a large % enough value. if abs(im(x,y))>0.05 im2(x,y) = ( 4*im(x, y) -... im(x-1, y-1) -... im(x+1, y+1) -... im(x+1, y-1) -... im(x-1, y+1) ); end end end % display the result of the operations subplot(212) imagesc(im2) colorbar Now change the values in the script, just for fun. What if you replace the value 0.05 for something else in this line of the code? if abs(im(x,y))>0.05 For extra credit, look up the commands else and case. We re not going to use them in this tutorial, but I would like for you to be aware of how the IF structure can be expanded to handle more than two choices. 11. End of First Tutorial There is a lot more to Matlab than what we ve covered today, obviously, but I hope that these few concepts will serve as a review of the basics and will get you started on your way to becoming a programmer. In the next couple of days we ll look at some very specific applications.