DOC PREVIEW
UCSD BENG 221 - Introduction to Matlab

This preview shows page 1-2-3-4-5 out of 14 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 14 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Introduction to MatlabWill Fox25 September, 2006Contents:1) Interacting with Matlab2) Arrays, aka Vectors3) Thinking in Matlab – vectorized indexing4) Thinking in Matlab – vectorized math5) Thinking in Matlab – vectorized testing6) Built-in functions and plotting7) For longer tasks - saving .m and .mat files, scripts, and functions8) Notes on scripts versus functions9) Continuing your education10) Essential Matlab commandsInteracting with Matlab% Matlab evaluates expressions5+5% Matlab can assign the result to a variablea = 5 + 5;% note that the semi-colon suppresses output. To get the answera% what variables does Matlab know about?who% this is the best way to find out about a without displaying itsize(a)% Answer: a is a matrix, with 1 row and 1 column, i.e. 1 elements% Everything in matlab is a matrix% some other simple operations:b = 2*a% This does exponentiation:c = a^2% some built-in functions, too, and% Matlab has a couple built-in constantspii% and built-in functionsa = pi/2d = sin(a)% Chapter 1 is doneclearArrays, aka Vectors% create arrays directly with the [ ] operationsfib = [1 1 2 3 5 8 13];% getting the array lengthlength(fib)% getting the size (surprise here!)size(fib)% Access elements of the array with ( ) fib(3)% For those who care: Matlab does unit-offset indexing of arrays% use the colon (:) operator to construct simple arrays simplyoneto10 = [1:10]odds = [1:2:11]zeroto1 = [0:0.05:1]% Language idea: the for loop.fib = [1 1]; % initialize arrayfor k=3:15fib(k) = fib(k-1)+fib(k-2);end% Matlab also lets us concatenate arrays fibfib = [fib fib]% main point[ ] is for array creation ( ) is for array subscripting (and for function calls, see later)Thinking in Matlab: Vectorized Subscripting% Getting the first three elements of fib% the C way to do itfib3 = [];for k=1:3fib3(k) = fib(k)end% the Matlab way to do itind = [1 2 3]fib(ind)% orfib([1 2 3])% get odd elementsfib(1:2:9)% better!fib(1:2:end)% reversefib(end:-1:1)Thinking in Matlab: Vectorized Math% want to compute squares% The C wayfibsq = []for k=1:9fibsq(k) = fib(k) * fib(k);end% matlab also allowsfibsq = []for k=1:9fibsq(k) = fib(k)^2;end% Better!fibsq = fib.^2% why .^ ?% _MAT_ lab - originally for matrices,% so ^ is reserved for strict matrix multiplicationThinking in Matlab: Tests and Vectorized Tests% First, we need to know about tests and test operations% remember assignment operationsa = 5% Now test. Watch what Matlab returns for true and falsea > 3a < 2a ~= 8% Matlab returns 1 for true, 0 for falseNote that == is not the same is =a == 5% if, then, else constructb = 0if (a == 5)b = 1;elseb = 2;endb% Let’s grab the elements of fib that are greater than 5fibg5 = [];for k = 1:length(fib)if fib(k) > 5fibg5 = [fibg5 fib(k)];endendfibg5% Let’s think in Matlab now% First, check out vectorized testsfib > 5fib == 5% Second, check out find.find(fib == 5)find(fib < 5)% Find returns the indices of the elements that are true.find([ 1 0 1 1 0] )% Elements of fib > 5, in Matlabindfibg5 = find (fib > 5)fib(indfibg5)fibg5 = fib(indfibg5)% NiceBuilt-in functions and Plotting% some functionssin, cos, tan, atan, exp, ...% to get a list of what matlab can do, tryhelphelp sinhelp elmat% Simplesin(pi/2)% It’s Matlab, so we like vectorized functionsx = pi * [ 0:4]sin(x)cos(x)% Demo plotting routines% open a new figure windowfigurex = [0:0.01:2*pi];plot(x, sin(x))plot(x, cos(x))% Gettting multiple plots on the same graphhold onplot(x, sin(x), ‘r’)% Clearing in the figureclfFor longer tasks...% We need to load and save files, and generally interact with the file system% Print the working directorypwd % change the working directorycd c:\will% show contents of the directoryls% use the matlab editoredit% Loading and saving your work to .mat filessave Sep23talk.mat fibclearlsload Sep23talk% Check out help load, help save for more options% Matlab lets you write scripts and functions% Script% fibscript.mN = 50;fib = [1 1]; % initialize arrayfor k=3:Nfib(k) = fib(k-1)+fib(k-2);end% try it outclearwhofibscriptwho% Things to watch out for: pathwhich fibscript% Now, do the same as a function.% fibfunction.mfunction fib = fibfunction(N)fib = [1 1]; % initialize arrayfor k=3:Nfib(k) = fib(k-1)+fib(k-2);end % try it outclearfib = fibfunction(50)fib = fibfuncton(100)Notes on scripts vs. functionsScriptsJust a list of matlab commands in a file.Executed in the present workspaceFunctionsHave private workspaceHave input and output parametersWhat you want depends on your taskScripts are for one-off things -You don't always want to be generic - sometimes you wantto be very particular about what you did, especially when you'regetting back to a problem after 6 mos.I like to save lots of scripts with descriptive names and datesThe ideal is to be able to open up matlab, cold call a script, and have somethingto play withExample – here is part one of my directories...loadAndFtData9Sep.m loadAndFtOverData24Aug.m loadAndFtOverData30Aug.m loadAndFtOverData31Aug.m loadAndFtOverData31AugB.m loadAndFtOverData7Sep.m loadAndOverBdata10Nov.m loadAndOverBdata9Nov.m loadAndOverData11Sep.m loadAndOverTe21Aug.m ....Functions are for repetitive tasksExample: one of my directories has fourierdelay.m fouriercoefs. fourierint.mfouriersum.mContinuing EducationOther Resourceswww.mathworks.comwww.octave.orgThings I haven’t coveredmore language elements while…end, break, case, try, … exotic plotting, loglog, semilogx, …3D plotting contour, surfaceexotic 3D plotting quiver…strings, help strfundisplaying disp, sprintffile access fopen, fread, fwritegraphical user interface creationmatrix math try help matfuninterfacing to external (e.g. C) codesignal processing fft, specgram, ……Alcator-Specific functions% open "LH" tree for "shot shot_number"stat = mdsopen('alcdaq::LH',shot_number); % retrieve data from the tree and assign it to variablex1=mdsvalue('\LH::TOP.HXR.RESULTS.COUNTRATE:CH01'); % close treemdsclose Done with Matlab?exitEssential Matlab commandsInteracting with the Matlab interpreter help ask Matlab about somethinghelp <command><Ctrl-C> try to stop a command <Up Arrow> cycle back through command historywho show variables in memorywhos ...with more detail on sizeclear clear all variables from memorysize(<array>) return dimensions of <array>Operation= assignment.*, .^, ./, remember to use “dot” for element-by-element ops+, - automatically element-by-element!==, ~=, <, etc tests


View Full Document
Download Introduction to Matlab
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Introduction to Matlab and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Introduction to Matlab 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?