首页 Matlab_for_Psychologists

Matlab_for_Psychologists

举报
开通vip

Matlab_for_Psychologists Matlab for Psychologists: A Tutorial Table of Contents Introduction ............................................................................................................................................. 2 Lesson 1 – The Basics .......................

Matlab_for_Psychologists
Matlab for Psychologists: A Tutorial Table of Contents Introduction ............................................................................................................................................. 2 Lesson 1 – The Basics ............................................................................................................................. 3 Lesson 2 - Matrices and Punctuation ...................................................................................................... 3 Lesson 3 - Indexing ................................................................................................................................. 6 Lesson 4 - Basic maths............................................................................................................................ 7 Lesson 5 - Basic functions....................................................................................................................... 8 Lesson 6 - Logical Operators .................................................................................................................. 9 Lesson 7 - Missing Data........................................................................................................................ 10 Lesson 8 - Basic Graphs........................................................................................................................ 11 Lesson 9 - Basic Scripts ........................................................................................................................ 13 Lesson 10 - Flow Control...................................................................................................................... 14 Lesson 11 - Functions............................................................................................................................ 16 Lesson 12 – More about variables......................................................................................................... 17 Lesson 13 - Advanced Graphs............................................................................................................... 19 Lesson 14 - How do I read this data file into Matlab? .......................................................................... 21 Lesson 15 - An example of a complete analysis script ......................................................................... 22 Exercise A: Data Manipulation ............................................................................................................. 23 Exercise B: Maths and functions........................................................................................................... 23 Exercise C: Logicals.............................................................................................................................. 24 Exercise D: A real data set ................................................................................................................... 24 Exercise E: Basic Graphs ...................................................................................................................... 25 Exercise F: Scripts and Functions ......................................................................................................... 25 Exercise G: Structures and cells ............................................................................................................ 26 Exercise H: More real data .................................................................................................................... 26 Glossary - Definitions ........................................................................................................................... 27 Glossary - Operators.............................................................................................................................. 28 Glossary - Basic Commands ................................................................................................................. 29 Glossary - Graphics functions ............................................................................................................... 29 Glossary - Statistics ............................................................................................................................... 30 1 Introduction Matlab is a language, and like all languages, the best way to learn is by using it. This tutorial starts off covering the basic grammar of Matlab, and then moves on to realistic examples and lots of exercises. It may seem slow to get started, but it really is worth persisting because once you know how to use Matlab, you will be able to: • analyze your data much quicker, more flexibly and with fewer errors than you ever could in Excel • Use Cogent to carry out experiments • Generate stimuli - pictures, sounds, movies, according to precise specifications • Write scripts for SPM so you can analyze your imaging data quickly and efficiently There are a couple of things to bear in mind before you start. There is no one right way to do anything in Matlab - lots of pieces of code may have the same effect, but as you get better it is worth looking for ways to make your code neat, then it will run quickly and be easy to debug. Starting from scratch on any project is very intimidating and the one of the best way's to start on Matlab is to take scripts that other people have written and adapt them to what you need. Some of the scripts in this tutorial may help, or ask people for their scripts (especially for SPM and Cogent). Getting started These notes assume that the reader uses Windows and has no programming experience. Linux / Unix users and people with experience of C - please be patient. Before you start, you should know that Matlab hates file names with spaces in (and so do I), so if you are going to use Matlab extensively, get used to using _ (underscore) instead of space in your file and directory names, and avoid keeping important files in the 'My Documents' folder or the Desktop in Windows. Make a folder directly in C: or D: or whatever and use that for your Matlab analysis – it will make your life much easier. Start Matlab by clicking on the icon on your desktop, and a variety of windows will open up. The main blank window is the command window, which has a prompt >> where you type your instructions to Matlab. I find it best to close all the other windows, except maybe the command history window, as the rest are a bit useless. The current directory is shown at the top of the command window, and you can change directories by clicking on the three dots to the right of it. You can also use the system commands ls, cd, dir and pwd to move between directories. As you read though this tutorial, try typing each line into Matlab, and if you don't understand what it is doing, try something else until you do. The only way to learn Matlab is by using it, so just try stuff. Though out this tutorial, things you can type into Matlab are show in green and Matlab's response is shown in blue. Words highlighted in red are (in general) defined in the glossary at the end. Getting help Matlab has a detailed help section, which you can access by clicking on the question mark at the top of the command window and searching. At any time, you can type help to get a list of categories of commands, for example type help general for a list of general commands. Type help followed by a command name to get more help on that command. For example: >> help length LENGTH Length of vector. LENGTH(X) returns the length of vector X. It is equivalent to MAX(SIZE(X)) for non-empty arrays and 0 for empty ones. 2 Lesson 1 – The Basics Matlab is based on a command line where you can see and manipulate variables. You enter commands at the prompt >> and Matlab responds. To create the variable A with the value 1 (N.B. spaces before and after = are optional). >> A=10 A = 10 A is now stored as a variable in Matlab's memory or workspace with the value 10. It can be used in sums etc >> A+A ans = 20 You can also put the result of a sum straight into a variable >> B = 5+8 B = 13 If you put a semi-colon at the end of the line, Matlab won’t show you the output of that command, but the value of the variable has still been changed. >> A = 15; Now type the name of the variable to see its new value: >> A A = 15 The name of a variable must begin with a letter, but can have numbers later in the name. Names are case-sensitive, and can be up to 32 characters long, but cannot have spaces or punctuation in the name. You can use underscore _ if you want a space, and there are certain reserved words like if which cannot be used as variable names. If you use a command name as a variable name, that command may not work and you will have to clear your variable to use the command To get rid of a variable, type clear followed by the name: >> clear B You can clear everything in the workspace by typing clear all The command whos shows you the variables that are in the workspace. You will see: Name: the name you use to refer to the variable Size: the number of rows (first number) and columns (second number) Bytes: how much memory the variable uses, but you don’t need to know that unless you are using very big variables. Type: all numbers are double arrays, but you can also use text, cell and logical (see later) >> whos Name Size Bytes Class A 1x1 8 double array ans 1x1 8 double array Grand total is 2 elements using 16 bytes You can clear the variables you have created with the command clear. Use clear var to remove just the variable var or use clear all to clear everything >> clear all Lesson 2 - Matrices and Punctuation If you are familiar with Excel, you will be used to the idea of putting all your data into a grid, and then adding up the rows or columns to do your analysis. Matlab lets you have as many grids or arrays as 3 you like, of any size, and each one is a variable with a name. You can then use the variable name to refer to the array when you want to manipulate it. Some types of array are: Scalar – a single number A = 10 Vector – a row or column of numbers B = 1 2 3 C = 4 3 8 Matrix – an array of numbers in a grid, its size is the number of rows x the number of columns. D is a 3 by 4 matrix. D = 5 6 7 9 8 3 5 3 5 6 3 2 Element – a single number within a matrix or vector. Brackets To enter most data into matlab, you need to use square brackets [ ] To put data into a row vector, type the values within square brackets, separated by spaces OR commas (or both). >> C = [6, 5, 8, 10] C = 6 5 8 10 To put data into a column vector, type the values in square brackets, separated by semi colons. In this context, semi-colon means 'start a new line'. >> D = [3; 1; 6; 5] D = 3 1 6 5 To put data into a matrix, use commas for the rows and then a semi-colon to start each new line. It is just like doing a row and column vector at once. >> E = [1, 2, 3; 4, 5, 6] E = 1 2 3 4 5 6 In general, square brackets are used any time that you want to join things together. See vertcat and horzcat for more information. Use round brackets ( ) to get things out of a matrix or to refer to just part of a matrix. For example, E(2,3) means the value in row 2, column 3 of E >> E(2,3) ans = 6 If you try to refer to something outside E, you will get an error message >> E(4,3) ??? Index exceeds matrix dimensions. 4 You can also use round brackets to change part of a matrix. To make the number in the 1st row and 3rd column of E be 10, type >> E(1,3) = 10 E = 1 2 10 4 5 6 And if you want to add a row or column to a matrix, you just need to refer to it and it will be created. Note that this only works if you are adding a row or column of the same size as your original matrix, if you try adding a different size, you will get an error message. >> E(3,:) = [7, 8, 9] E = 1 2 10 4 5 6 7 8 9 Colon The colon character : means several different things in Matlab. In round brackets, a colon means everything in a row or column and is normally used to extract data from a matrix. E(:,2) means everything in column 2 of E. Read this as 'E, every row, column 2' >> E(:,2) ans = 2 5 8 E(2,:) means every column in row 2 of E. Read this as 'E, row 2, every column' >> E(2,:) ans = 4 5 6 A colon in brackets by itself turns anything into a column vector. E(:) rearranges everything in E into one long column >> E(:) ans = 1 4 7 2 5 8 10 6 9 Between two numbers, the colon means count from A to B one integer at a time >> F = 5:10 F = 5 6 7 8 9 10 You can use a colon like this to extract data from a matrix too. For example, F(:,3:5) means everything in columns 3, 4 and 5 of F >> F(:,3:5) ans = 7 8 9 5 A set of three numbers with a colon specifies the step to use for counting, e.g. G = 3:4:20 means G counts from 3 to 20 in steps of 4 >> G = 3:4:20 ans = 3 7 11 15 19 Type help punct, help colon and help paren for more information on matrix punctuation in matlab. The Array Editor I never use the array editor in Matlab, but when you are making the transition from Excel, you may find it helpful. Use the menus to select View - Workspace and Matlab will show you a window listing all your variables and their sizes, similar to typing whos. Then if you click on a variable, the Array Editor window opens. This shows you the data in a grid a bit like Excel, and any numbers you change here will be changed in Matlab's memory, while commands at the command prompt which change the variable you are looking at will automatically be shown in the array editor. You can also paste data from another program (like Excel) into a Matlab variable here. Lesson 3 - Indexing Indexing means getting the part of a matrix you want, and it is crucial to Matlab. The easiest way to get the data you want is to use subscripts, i.e. to tell Matlab the rows and columns that you want. For this example, we will use a magic square matrix which is stored in Matlab and accessed with the command magic. >> clear all >> A = magic(5) A = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 We can extract the value in row 4 column 3 from A, using round brackets >> B = A(4,3) B = 19 or just row 4, read this as C is A, row 4 all columns >> C = A(4,:) C = 10 12 19 21 3 We can extract rows 2 and 3 from A. Read this as B is A, rows 2 and 3, all columns. The square brackets and semi-colon are used to join the required rows together and the round brackets to extract the rows from A. >> D = A([2;3],:) D = 23 5 7 14 16 4 6 13 20 22 And we can extract columns 1 to 3 of D. Read this as E is D, all rows from columns 1 through 3 >> E = D(:,1:3) E = 23 5 7 4 6 13 We can also use indexing to put values into A, e.g. to make row 2 column 2 of A equal 100, use: 6 >> A(2,2) = 100 A = 17 24 1 8 15 23 100 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 To make all of column 4 of A equal 0, use >> A(:,4) = 0 A = 17 24 1 0 15 23 100 7 0 16 4 6 13 0 22 10 12 19 0 3 11 18 25 0 9 You should now know enough to do Exercise A Lesson 4 - Basic maths Type clear all before starting this section, and enter enter E = [1, 2, 3; 4, 5, 6] and A=10. In matlab, you can do sums on numbers or on variables. Variables are treated just like the number (or numbers) they represent. Most things are as you would expect: + means plus - means minus ' means transpose (turn rows into columns and vice versa) ( ) round brackets can be used to specify the order of operations according to BODMAS BUT * means matrix multiplication / means matrix division You are more likely to want to dot-multiple and dot-divide .* means element-wise multiplication ./ means element-wise division .^ means power (i.e. A.^2 means A squared) You can do sums on single numbers just by typing in the command line. Spaces before and after the signs are optional. >> 174 .* 734 ans = 127716 >> (A*2) / 5 ans = 4 You can also do sums between a scalar and a matrix. The sum will be applied to every value of the matrix. >> J = E*A J = 10 20 30 40 50 60 You can add and subtract matrices if they are the same size: >> K = J – E ans = 9 18 27 36 45 54 7 You can multiple or divide elements of two matrices using .* and ./ The matrices must both be of the same size, otherwise you will get an error message. >> L = [3 2 1; 9 5 6] L = 3 2 1 9 5 6 To divide each value of K by the value in the equivalent place from L: >> K./L ans = 3 9 27 4 9 9 To multiply each value of E by the value in the equivalent place from L: >> E.*L ans = 3 4 3 36 25 36 Note that using * and / without the . will perform matrix multiplication and division, where whole rows and columns are multiplied and summed. This is described in linear algebra text books, but you are unlikely to need it for basic data analysis. If you multiply and you get back a matrix of a different shape, you’ve probably done matrix multiplication. If your matrix is square (has the same number of rows and columns), be extra careful because matrix multiplication won't produce an obvious error. Type help elfun (elementary functions) help ops (operators) or help arith (arithmetic) for more information on basic maths with Matlab. Lesson 5 - Basic functions Matlab has a large number of build in functions which allow you to perform simple maths and to generate matrices quickly and easily. Functions are bits of code (written by you or Matlab or anyone) which receive some inputs and give you some outputs. They use round brackets, and all functions written by Matlab have help files to tell you how to use them. Type help followed by the command name for details. All functions have one or more inputs or arguments and produce one or more outputs. If a function has just one output, the output can be placed straight into a variable, but if a function has several outputs, square brackets are needed to group the output variables. All functions have the form: [output1, output2, ...] = function (arg1, arg2, ...) All the mathematical functions you need to operate on single values are available, e.g sin, cos, tan, sqrt, log and pi. Matlab has a variety of useful functions which you can apply to the rows or columns of a matrix, including sum, mean, std, max and min. By default, these work on columns, but you can change the dimension to work on rows. Type help followed by the function name to see how to do this. To sum the columns of K: >> sum(K) ans = 45 63 81 To sum the rows of K, you must tell the sum function to operate in the 2nd dimension (1st = columns, 2nd = rows) >> sum(K,2) ans = 54 135 8 To find the mean of J and put it in a variable >> mj = mean(J) mj = 25 35 45 The apostrophe is useful to transpose a matrix or vector, i.e. to turn all the rows into columns and the columns into rows >> K' ans = 9 36 18 45 27 54 There are also a set of functions to create vectors and matrices. These include rand, ones, zeros, repmat, ndgrid, linspace, logspace and magic. e.g. To create a matrix of random numbers with
本文档为【Matlab_for_Psychologists】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_217216
暂无简介~
格式:pdf
大小:278KB
软件:PDF阅读器
页数:30
分类:教育学
上传时间:2011-09-11
浏览量:105