cnbc matlab mini course why should you learn matlab
play

CNBC Matlab Mini-Course Why Should You Learn Matlab? Data analysis: - PDF document

CNBC Matlab Mini-Course Why Should You Learn Matlab? Data analysis: Much more versatile than a spreadsheet. Extensive statistics toolbox. David S. Touretzky SPM uses Matlab. September 2019 Graphics: Many ways to visualize


  1. CNBC Matlab Mini-Course Why Should You Learn Matlab? ● Data analysis: ● Much more versatile than a spreadsheet. ● Extensive statistics toolbox. David S. Touretzky ● SPM uses Matlab. September 2019 ● Graphics: ● Many ways to visualize your data – even animations! Day 1: Essentials ● Produce great figures for your papers. ● Modeling and simulation: ● Best choice for neural net simulations. 1 4 What Is Matlab? Getting Started ● Product of The Mathworks, Inc. ● Log in to a workstation. ● Go to the menu bar at the top of your screen http://www.mathworks.com and select: ● Runs on Linux, Windows, and Macs. Applications > Education ● Student version just $49 (plus toolboxes). > MATLAB ● Latest release is Matlab R2019b. ● “Interactive” interface like BASIC, Python, Lisp, etc. Type in expressions and see the result. 2 5 What Is Matlab? (cont.) Variable Creation ● Full programming language. a = 5 ● Strong on matrix manipulation and graphics. ● Optional toolboxes for statistics, image a = 6 ; processing, signal processing, etc. single quote ● Interfaces with C, Fortran, and Java. b = 'penguins love herring' ● Can create stand-alone executable files. – HHsim, a Hodgkin-Huxley simulator developed by Dave who Touretzky with help from Jon Johnson, is distributed as a Click on the stand-alone executable. (Source is also available.) Workspace tab for a graphical version of whos. whos 3 6

  2. Matrix Creation Subscripting x = [1 2 3 ; 9 8 7] V = [10 20 30 40 50]; zeros(3, 5) V(3) index from 1, not 0 zeros(5) zeros(5, 1) column vector M = zeros(1, 5) row vector 1 2 3 M = [1 2 3; 4 5 6; 7 8 9] 4 5 6 7 8 9 ones, rand, randn, eye M(2,2) What does eye do? M(2) access in column-major order M(6) 7 10 Colon Creates Row Vectors Matrix Slices 1 : 5 V(2:4) 1 : 3 : 15 V(2:end) 10 : -1 : 0 M(1:2, 2:3) pts = 0 : pi/20 : 4*pi; M( : ) M(: , :) 8 11 Size of a Matrix Expanding a Matrix whos pts a = [1 2 3] size(pts) a = [a 4] Efficiency tip: Use ZEROS(rows,cols) length(pts) a(7) = 5 to preallocate large arrays instead of growing them dynamically. a(end+1) = 6 b = [a ; a.^2] 9 12

  3. Reshaping a Matrix Deleting Rows or Columns M = reshape(1:15, 5, 3) M(: , 3) = [ ] M' M(2, :) = [ ] M' ' or (M')' size([ ]) 13 16 Command Line Editing Exercise ● Arrow keys work like you expect ● Create the following matrix using only the ● Basic Emacs commands also work: colon, reshape, and transpose operators. Forward/back char ^F / ^B 1 2 3 Left/right word alt-F / alt-B 4 5 6 Beginning/end of line ^A / ^E 7 8 9 Delete forward/back char ^D / backspace 10 11 12 Clear line ^U 13 14 15 Kill to end of line ^K Undo ^_ ● Environ. > Preferences > Keyboard > Shortcuts for a list, or to switch to Windows conventions. 14 17 Adding Rows vs. Columns Command Line History ● Scrolling through the command history: M = [1 2 ; 3 4] Move to previous command ­ Move to next command ¯ M = [M ; 5 6] ● Can also double click (or click and drag) on an item in the Command History window V = [10 20 30] ' ● Command/function completion: cle<tab> M = [M V] ● Interrupt execution: ^C M = [M [99; 98; 97] ] 15 18

  4. Editing Files in Matlab Multiple Plots New > Script clf hold on Put 3+5 on the first line plot(pts, sin(pts)) Put m = magic(5) on the second line plot(pts, cos(pts), 'm') plot(pts, cos(pts), 'go') Save the file as foo.m in the current directory. legend('sin', 'cos', 'pts') Type foo in the Command Window Click and drag to position the legend. 19 22 Basic Plotting Summary of Plot Options pts = 0 : pi/20 : 4*pi ; ● Colors: r,g,b,w c,m,y,k plot(sin(pts)) ● Symbols: . o x + * s(quare) d(iamond) etc. plot(pts, sin(pts)) ● Line type: - (solid), -- (dashed), : (dotted), -. (dash-dot) axis off / on grid on / off box off / on help plot whitebg(gcf, [0 0 0]) clf clf reset 20 23 Plot Labeling Printing ● On the File pulldown menu, select Print . pl^P ● Or type ^P in the figure window. xlabel('Angle \theta') ● Printing to a file: print -djpeg myfig.jpg ylabel('y = sin(\theta)') print -depsc -r300 myfig.ps print -dtiff myfig.tiff title('The Sine Function') ● To learn more: help print 21 24

  5. Plotting With Error Bars Writing Your Own Functions clf New > Function function [ y ] = parabola( x ) % PARABOLA Computes a quadratic. y = sin(pts); % Y = parabola(X) May be called with a vector. y = x .^ 2; e = rand(1, length(y)) * 0.4; Save as parabola.m Try: parabola(5) help parabola errorbar(pts, y, e) clf, plot(parabola(-10 : 10),'r--s') parabola Gives an error message. Why? 25 28 Multiple Figures Scripts vs. Functions ● Scripts take no input arguments and produce figure no return values. bar3(abs(peaks(7))) ● Scripts operate in the workspace of their caller. figure(5) ● If called from the command line, scripts operate in the base workspace . delete(2) ● If called from within a function, scripts operate in the function's local workspace and can see Or type ^W in a figure window to close it. and modify its local variables. 26 29 Histograms Scripts vs. Functions ● Functions can take zero or more arguments dat = randn(10000, 1); and return zero or more values. hist(dat) ● Functions operate in their own local workspace . hist(dat, 50) ● Variables created inside a function are local to that function. b = hist(dat, 6) ● Local variables disappear when the function bar(b) returns. 27 30

  6. Logical Operations Control Structure: FOR Loops Operators: == ~= < > <= >= for i = 1 : 5 [ i i^2 ] Can't use != as in Java or C end Logical values: 0 means “ false ” 1 (or any non-zero number) means “ true ” clf, hold on for x = pts plot(x, cos(x), 'kd') pause(1) a = (3 >= 1 : 5) What are the type and size of a? end (you can use ^C to terminate the loop) 31 34 Boolean Subscripting Control Structure: WHILE Loops V = [1 2 3 4 5]; How quickly can a random accumulator reach 5? V(logical([1 0 1 1 0])) accum = 0; steps = 0; V( V >= 3 ) while accum < 5 steps = steps + 1; V( V >= 3) = 0 accum = accum + rand(1); end S = 'banana cabana' steps, accum S( S == 'a') = [ ] 32 35 The IF Statement Element-Wise Arithmetic Differences from C/C++/Java: if x >= 3 Element-wise operators: + − .* ./ .^ y = x; No ( ) parens around the else Dot means condition expression. M = rand(5,3) “element-wise” y = x + 3; hadHelp = true; No { } braces around the M + 100 end then/else clauses. M .* 5 same as M * 5 Requires end keyword. M .* M not same as M * M M ./ M Short form – use commas or semicolons: M .^ 2 if x>3, y=x; else y=x+3; hadHelp=true; end 33 36

  7. Matrix Arithmetic Reduction Operators m1 = rand(5,3) M = rand(5, 3) m2 = rand(3, 5) sum(M) m1 * m2 (5×3) * (3×5)  (5×5) sum(M, 2) sum along 2 nd dimension m2 * m1 (3×5) * (5×3)  (3×3) m1 * m1 Error! Shapes don't fit. m1 / m2 Error! Shapes don't fit. sum, prod, min, max, mean, var m1' / m2 min(min(M)) pinv(m1) (5×3)  (3×5) min( M(:) ) 37 40 Exercise: Data Plotting Script Expanding with REPMAT ● REPMAT is often used to expand a vector to fit x = 0 : pi/20 : 5*pi ; y = sin(x) + x/3 + randn(1,length(x))/4; the shape of a matrix. z = smooth(y,20)' ; ● Example: adjusting a dataset to have zero clf, hold on mean. plot(x, y, 'bo--') M = rand(5, 3) plot(x, z, 'm', 'LineWidth', 3) avgs = mean(M) Mavgs = repmat(avgs, 5, 1) Save as mydata.m and run it several times. Mzero = M – Mavgs sum(Mzero) 38 41 Exercise (cont.) Exercise ● Suppose we want the rows of M to sum to zero, Now add these additional lines: instead of the columns. maxL = [1, z(2:end) > z(1:end-1)] ; maxR = [z(1:end-1) > z(2:end), 1]; ● How would you do this, without using the localMax = maxL & maxR; % true if point is local maximum transpose operator? px = x(localMax); px(2,:)=0; px(3,:)=NaN; pz = z(localMax); pz(2,:)=z(localMax); pz(3,:)=NaN; plot(px, pz, 'r') For homework: figure out how it works. 39 42

  8. Matlab Documentation help cos doc cos clf, peaks click on rotate3D icon Yes! which peaks You CAN see edit peaks our source code! Introductory Text Examines a variety of neuroscience applications, with examples. lookfor rotate 43 46 Browsing Online Documentation Ways To Learn Matlab ● Three more days of this mini-course. ● Press F1 to bring up the Documentation Browser ● Tutorial videos at mathworks.com ● In the documentation browser: ● Built-in demos: > Statistics and Machine Learning Toolbox doc demo > Probability Distributions ● Browse the online documentation > Continuous Distributions ● Dozens of books: > Beta Distribution Amazon.com reports 7,900 search results! > (Concepts) Beta Distribution ● Matlab Central: user community site http://www.mathworks.com/matlabcentral ● Questions to support@mathworks.com 44 47 MATLAB Primer, 8 th ed. Timothy A. Davis CRC Press $10.86 at Amazon Handy pocket reference. 45

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend