为了正常的体验网站,请在浏览器设置里面开启Javascript功能!
首页 > Matlab官方速成

Matlab官方速成

2010-06-02 18页 pdf 542KB 21阅读

用户头像

is_657802

暂无简介

举报
Matlab官方速成 The Official MATLAB Crash Course Written mostly by Adam Attarian (arattari@unity) May 27, 2008 As you may have heard, MATLAB is a powerful platform for mathematical and scientific computation. Compared to C or JAVA, it has an easy to use programming interface a...
Matlab官方速成
The Official MATLAB Crash Course Written mostly by Adam Attarian (arattari@unity) May 27, 2008 As you may have heard, MATLAB is a powerful platform for mathematical and scientific computation. Compared to C or JAVA, it has an easy to use programming interface and many, many built in functions to do tons of different things. If you can learn its syntax and language now, it will pay off greatly for you in the future. We’ll take you through an overview of its usage, and then focus on certain areas that you’ll be likely to run into sooner rather than later. 1 General Usage & Overview 1.1 Interacting with MATLAB When you first open MATLAB, notice the command window, workspace, and command history. The command window is where you’ll give MATLAB its input and view its output. The workspace shows you all of your current working variables and other objects. Notice the help menu. This will become your favorite menu. Just some housekeeping commands: to clear your command window, type clc. To clear your workspace (this is like resetting everything – use with caution), type clear. You can also clear a specific variable: just follow the clear command with the variable name. To move around, use the standard UNIX commands. To change directories, use the cd com- mand. To go back up a directory, use cd .. . To figure out where you are, type pwd. On the Unity Macs, you’re automatically placed in the MATLAB Application folder when you use MATLAB. Problem is, you don’t have write privileges there, so to get into your home directory, type cd ∼. 1.2 Entering Data On the surface, MATLAB is a huge, expensive, glorified, calculator. Everything (well, mostly) in MATLAB is created and treated as a matrix (MATLAB is short for MATrix LABoratory). MAT- LAB has the standard arithmetic operators that you’d expect: +, −, ÷, ×, and exponentiation, ˆ. To suppress the output (e.g you don’t want to see the result), end your command with a semicolon. To enter a vector, put the input in brackets. For instance, to create a row vector in R4, you could enter: >> A=[4,1,5,6]; We have just assigned the vector [4, 1, 4, 6] to the variable A. MATLAB is case sensitive, so the variable a6=A. If you wanted to make that a column vector, just use semicolons instead of colons, 1 or transpose the vector using the ’ operator. To enter a matrix, stick some rows together. For example, a 2× 2 matrix B could be entered as: >> B=[1 2; 3 4] This enters the matrix B = ( 1 2 3 4 ) Some vectors would be unpleasant to type in all of their glory, and MATLAB understands that. For example, to obtain the vector t = [0 .5 1 1.5 2 . . . 9 9.5 10], you would type t=[0:.5:10], which creates a vector from 0 to 10 in half increments. Or, to get a vector containing equally spaced entries, you can use the linspace command. For example, to get 400 linearly spaced entries from 0 to 100, you could type >> r=linspace(0,100,400). Some special cases: • A scalar does not need brackets. g=9.81; will suffice. • Square brackets with no elements (X=[]) creates a null matrix. Can be useful to delete rows/columns of a matrix. Example: if you wanted to delete the 4th row of matrix A, you could say A(4,:)=[]; Since everything in MATLAB is a vector or a matrix, it makes sense to be able to extract data from certain points of a vector. For instance, to obtain the 5th entry of a vector r, type >> r(5). For a range of values, say from a to b, type >> r(a:b). For a matrix, the syntax is (row, column). So to get the i, j entry of the matrix B, type >> B(i,j). Similarly, you can pull out ranges of values as you could with a vector. If you wanted the entire range of rows, or columns, use the colon. So the rowspace of the fourth column of A would be A(:,4). 1.3 Operations You’ll be pleased to know that the standard operations, sin, cos, tan, arctan, log, ln, and exp (all are not listed here) exist in MATLAB. You can apply these to vectors, matrices, whatever. If you wanted the sine of a vector, just do b=sin(a). Some things to know: • The log command is the natural log. For log10, use log10. • e is not a protected operator. If you want e5, use exp(5). • MATLAB recognizes i and j as the imaginary unit. • Matrix multiplication works as you’d expect, so long as the dimensions match of course. To multiply 2 matrices A,B just do >> C=A*B. MATLAB can also do element wise operations on matrices and vectors using the dot notation. For example whereas >> C=A*B is standard matrix multiplication, >> C=A.*B will create a matrix C whose elements are defined as cij = aij ·bij . The dot notation works with multiplication, *, division, /, and exponentiation. You’ll have to use this more often than you think. 2 1.4 Very Useful/Helpful Functions Since you have the hard way to do things, here are some easy ways: • size() returns the dimension of a matrix/vector. If you just want the length of a vector, use length(). • eye(n) creates the n× n identity matrix. • zeros(n,m) creates an n ×m matrix of zeros. Useful for initializing vectors and matrices. Similarly, ones(n,m) creates a matrix of ones. • rand(n,m) creates a n × m matrix with entries from a uniform distribution on the unit interval. • randn(n,m) same as above, just now from a normal gaussian distribution. So for example, entering >> B=[ones(3) zeros(3,2); zeros(2,3) 4*eye(2)]; Produces the matrix  1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 4 0 0 0 0 0 4 . Exercise: Create the following matrices: A =  1 2 34 5 6 7 8 9  , B =  1 2 10 1 0 4 5 9  , C = [ 1 0 0 1 ] Try some of these basic operations and see what happens: A ∗B,A. ∗B, 2 +A,A+B. Now create a vector and a matrix with the following commands: v=0:0.2:12; M=[sin(v); cos(v)];. Find the sizes of v and M using the size command. Extract the first 10 elements of each row of the matrix and display them as column vectors. 2 Plotting Data / Making Pretty Pictures Some say your data is only as good as you can make it look, so it is important to make it look good. The most basic way to plot 2D data is using the plot command: >> plot(x, y, options ), 3 where x is a vector defining the independent vector and y is the data you want to plot and options is where you can specific all kinds of well, options, for your plot (type >> help plot for more on that). For example, if you want to plot sin(x) on the interval [0, 2pi], you would type >> x=[0:.1:2*pi]; >> y=sin(x); >> plot(x,y); You can also plot several sets of data on the same figure, assuming each vector is the same length. One way is to use the plot command like so: plot(x1,y2,x2,y2). Another (perhaps better) way is to use the hold command, which holds the plot on the current figure: >> plot(x1,y1) >> hold on >> plot(x2,y2) Since the beginning, we’ve been taught to label our plots. MATLAB allows you to do this through the command line or through the user interface. We could label and legend our sine plot like so: >> xlabel('x'); >> ylabel('sin(x)'); >> title('My First MATLAB Plot'); >> legend('sin(x)','Location','SouthWest');} Notice the location tag on the legend. This puts the legend in the lower left corner. Do help legend for more. 2.1 More on Plotting Lets take a moment to delve a little more deeply into the art of generating plots in MATLAB. We can do a lot with our plots: we can change the linewidth, change the color, change the fonts (and size) of the titles, use LATEX notation, and much more. You can either do this via the user interface, or on the command line. • LineWidth. To increase the thickness of the traces on the plot, add in the LineWidth option: plot(x,y,’LineWidth’,2). This will plot with a line width of 2. • Changing Fonts. You can probably tell what is going on by this example: title(’My Awesome Plot’,’FontName’,’courier’,’FontSize’,20,’FontStyle’,’bold’);. The font will be Courier, at size 20, bolded. Substitute your favorite in as you so desire. 4 • LATEX Inclusion. MATLAB, by default uses TEX to render the axes and titles, which can be inadequate when we’re used to using LATEX characters. To get around this, we need to specify the LATEX interpreter. If I wanted to have ∂u∂t = e −t as the title to my plot, I would use title(' ∂u ∂t = e−t','Interpreter','Latex'); • Axes. MATLAB gives you a few ways to modify your axes. xlim and ylim take a range vector as an input and will adjust your axes accordingly. To do it all at once, you can do axis([xlow xhigh ylow yhigh]). • Grids. Type grid on (and off) to get a grid on your plot. Useful for journal quality plots. • Subplots. Use these. You can display multiple plots in the same figure window and print them on the same piece of paper with this function. Check out this plot: −1 0 1 −1 −0.5 0 0.5 1 0 2 4 6 −2 −1 0 1 2 0 2 4 6 −1 −0.5 0 0.5 1 0 2 4 6 −1 −0.5 0 0.5 1 This is the code that was used to generate the plot: t=0:pi/20:2*pi; [x,y]=meshgrid(t); subplot(2,2,1) plot(sin(t),cos(t)); axis equal; subplot(2,2,2) z=sin(x)+cos(y); plot(t,z); axis([0 2*pi −2 2]); subplot(2,2,3) 5 z=sin(x).*cos(y); plot(t,z) axis([0 2*pi −1 1]); subplot(2,2,4) z=(sin(x).ˆ2)−(cos(y).ˆ2); plot(t,z); axis([0 2*pi −1 1]) subplot(m,n,i) creates an m× n array of plots, and then you count through them with i, counting from left to right, top to bottom. Each subplot is rendered independently of the rest. • Surface and 3D plots. There are two types of R3 plots in MATLAB, surface plots, and line plots. An example of a line plot is given in the next exercise where you plot a helix. Some examples of surface plots are mesh, surf, surfl, waterfall, and there are more. To really use these plotting tools, you’ll need to know about meshgrid. meshgrid transforms vectors into arrays so that you can evaluate functions in R2 and plot them with these commands. Compare the plots below: 0 50 0 20 40 !6 !4 !2 0 Mesh Plot 0 50 0 20 40 !6 !4 !2 0 Waterfall Plot 0 50 0 20 40 !6 !4 !2 0 Surf Plot 0 50 0 20 40 !6 !4 !2 0 Meshz And the code used to generate: x=linspace(−3,3,50); y=x; [x,y]=meshgrid(x,y); z=−5./(1+x.ˆ2+y.ˆ2); subplot(2,2,1) 6 mesh(z); title('Mesh Plot') subplot(2,2,2); waterfall(z); title('Waterfall Plot'); hidden off; subplot(2,2,3); surf(z); title('Surf Plot'); subplot(2,2,4); meshz(z); title('Meshz'); Lastly, to export your figures for use in LATEX and other nice programs, be sure to save the figures as EPS format. This way, you can use them in your TEX documents with no problem at all. Exercise: Plot the sine and cosine functions on the interval [0, 2pi] on the same graph. Use different colors and line styles for each trace, and label all aspects of the plot. Investigate and use the legend command. Also, MATLAB can also plot 3D data with the plot3(x,y,z) command. Try and use this command to plot the standard helix, where x(t) = sin(t), y(t) = cos(t), z(t) = t on the interval t ∈ [0, 20]. 3 M-Files, Scripts, and other files Up until now, we’ve been entering commands in the command window, one line at a time. While this may work for a few commands or if you’re testing something, this definitely won’t work for longer programs or anything remotely complicated. To get around the command window, we can type things up in m-files, and then call and run the m-file from the command line. There are two main types of m-files that we’ll be using: script files, and function files. The differences are big: • Script files can use any and all variables in the workspace when the script is run, and any results of the script are leftover in the workspace when complete. • Functions can take dynamic inputs, but all variables are local to the function and are not explicitly saved in the workspace when complete. Why is this important? We’ll talk about it. To write an m-file, you can either use your favorite text editor on your computer or (even better) the builtin MATLAB file editor. To get started, you can either click the new file button in the main MATLAB window, or type >> edit myscript, (myscript being whatever you want to call your new m-file) and then you can go from there. Also, 7 anything behind an % is a comment and is thusly ignored by MATLAB. Comment your code as much as you can! Here is an example of a script that plots the unit circle: % CIRCLE − A script to draw the unit circle % −−−−−−−−−−−−−−−−−−−−−−−−−−−−− theta=linspace(0,2*pi,100); % create a vector x=cos(theta); % generate x−coords y=sin(theta); % generate y−coords plot(x,y,0,0,'+'); %plot data and put a + at the origin axis('equal'); % set equal scale on axes title('Unit Circle Plot');} This is a script file. To run it, simply type circle at the command line. Note that you have to be in the same directory as the file in order for it to run. A function file is also an m-file, except that all the variables are local. A function file begins with a function definition line, which as a well-defined list of inputs and outputs. Without this line, the file is simply a script. The syntax is: function [output variables ] = function name( input variables) where the function name must be the same as the filename (without the .m extension). For example, the function definition function [rho,H,F] = motion(x,y,t) takes (x, y, t) as inputs and can return the variables (ρ,H, F ) to the user. To execute this example function, you would type: >> [r, angmom, force] = motion(xt,yt,time); The input variables xt, yt, time must be defined beforehand, and the output variables will be saved in r, angmom, force. Exercise: Turn the circle.m script file above into a function that accepts an arbitrary radius r, and plots the resulting circle. 4 Basic MATLAB Programming Things can get complicated quick in MATLAB. Knowing some basic programming techniques can really speed things along. We’ll go over loops, global variables, and conditional boolean algebra (what?). 4.1 For Loops There are two kinds of loops we’ll use: for and while loops. A for loop is used to repeat a statement of a group of statements for a fixed number of times. An example: 8 for m=1:100 num = 1/(m+1) end This will print out the value of 1m+1 for 1 ≤ m ≤ 100. The counter in the loop can also be given by an explicit increment, like for i=m:k:n, to advance the counter i by k each time. You can have nested for-loops, but each must match with its own end. 4.2 While Loops A while loop is used to execute a statement or a group of statements for an indefinite number of times until the condition specified by while is no longer satisfied. An example! % find all the powers of 2 below 10000 v=1; num=1; i=1; % initialize while num < 10000 num = 2ˆi; v = [v; num]; % save the result i = i+1; % increment the counter end Once again, a while loop needs a matching end statement. 4.3 If Statements Frequently you’ll have to write statements that will occur only if some condition is true. This is called a branch statement. Typically you’ll have an if statement, and if it isn’t satisfied, a corresponding else or elseif statement. Along with the standard greater than, and less than conditions (a>b, b=b, b<=a), there are also: • and: a & b • or: a | b • not-equal: a ~= b • equal (notice the two equal signs!): a==b Observe: i=6; j=21; if i >5 9 k=i; elseif (i>1) & (j==20) k=5∗i+j; else k=1; end Of course you can (and probably will) nest if statements, as long as you have matching end statements. Lastly, you can define variables to be global. This is handy if you want one function to be able to access another variable, and vice-versa. To declare a variable, just say >> global variable-name . You’ll have to make this declaration wherever you want access to the variable. 4.4 Debugging Output Sooner or later, you’ll have to debug your code. One thing that may help in this endeavor is the disp() command. disp() merely displays its input to the command window. Try >> disp(’Hello World!’);. Sticking a disp on key lines of your program can help you trace where MATLAB is when it gets stuck. Other useful commands in this department: • num2str(): converts a double number to a string. If you want to display a number in a string, you’ll need this function. • str2num(): goes the other way. Useful for when you import strings of number from a file. In order to do anything with them, they have to be converted to doubles first. Exercise: Create a 10× 10 random matrix. Then, have some fun by: • Multiply all elements by 100 and then round off all elements of the matrix to integers using the fix command. • Replace all elements of A < 10 with zeros. Maybe use the find and the sub2ind command? • Replace all elements of A > 90 with infinity (inf). • Extract all 30 ≤ aij ≤ 50 in a vector b, that is, find all elements of A that are between 30 and 50 and put them in a new vector. Next, simulate a random walk. Say someone can walk right or left. They flip a coin. If heads, they take a single step right, tails they go left. The individual does this 5000 times. Can you plot the path? What if the coin were weighted to one side? Welcome to Monte-Carlo simulations. 10 5 Linear Algebra Since everything in MATLAB is a matrix, it makes sense that MATLAB would be well-suited to linear algebra problems. For example, to solve the common problem Ax = b, where dim(A) = n×m, and x, b are vectors m long, you can simply type >> x=A\b. Consider the system: 5x− 3y + 2z = 10 −3x+ 8y + 4z = 20 2x+ 4y − 9z = 9 Its coefficient matrix is A =  5 −3 2−3 8 4 2 4 −9  And the known constant vector is b = [10 20 9]T . To solve this system in MATLAB: >> A=[5 −3 2; −3 8 4; 2 4 −9]; >> b=[10; 20; 9]; >> x=A\b x = 3.4442 3.1982 1.1868 Note that the backwards division operator is equivalent in usage to inv(A)*b. Some other useful linear algebra related commands: • rref(C): finds the reduced row echelon form of the matrix C • inv(A): computes the inverse of the matrix A, assuming it exists. Note you should nearly never have to explicitly compute an inverse of a matrix. They almost got rid of this command. • det(A): finds the determinant of an n× n matrix A. • [V,d]=eig(A): finds the n × n matrix V whose columns are eigenvectors and D is an n × n matrix with the eigenvalues of A on the diagonal. Solves the problem Av = λv. • Built-in matrix factorizations: [L,U]=lu(A), [Q,R]=qr(A). • diag(v): generates a diagonal matrix with vector v on the diagonal. diag(A) extracts the diagonal of matrix A as a vector. 11 6 Solving ODEs One of the more prolific problems that we’ll deal with in MATLAB is numerically solving and plotting systems of ordinary differential equations (ODEs). MATLAB can only solve first order ODEs, so if you have higher order systems you’ll have to devolve them to first order equations; we’ll cover this below. The basic syntax for solving an ODE in MATLAB is: [time, solution] = ode45(@odefun,[tspan],[ic],options,parameters ) where ode45 is one available solver (a 4-5 order Runge-Kutta Method), odefun is your ODE file (more on this shortly), tspan is either an interval or a vector where the ODE will be solved, ic is an initial condition vector, and options are ODE specific options, such as tolerances. Solving most ODEs in MATLAB requires you to: 1. If the order is greater than 2, write the differential equations as a set of first order ODEs. This just involves introducing some new variables. 2. Write a function to compute the state derivative. The state is the variable that you are trying to solve for by integrating the differential equation. This function needs to return out the state derivative x˙. 3. Call the solver, extract the desired variables, use knowledge to understand what is happening. 6.1 Example 1: A Trivial Case Consider the most fundamental differential equation out there, written in all our favorite notations: dy dt = y(t) ⇐⇒ y˙ = y ⇐⇒ y′ = y An introductory calculus class tells us that the solution to
/
本文档为【Matlab官方速成】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索