50 likes | 57 Vues
Variables and Assignments Vectors and Matrices. Solving Equations Functions. MATLAB Basics I. Yun Suk Jang Department of physics Kangwon National University. You use the equal sign to assign values to a variable. >> x = 7 x = 7 X the value 7 from now on.
E N D
Variables and Assignments Vectors and Matrices Solving Equations Functions MATLAB Basics I Yun Suk Jang Department of physics Kangwon National University
You use the equal sign to assign values to a variable. >> x = 7 x = 7 X the value 7 from now on. If y has been defined as a symbolic variable, then >> x^2 - 2*x*y + y ans = 49 – 13*y To clear the value of the variable x, type clearx. You can make very general assignments for symbolic variables and then manipulate them. >> clear x; syms x y >> z = x^2 – 2*x*y + y z = x^2 – 2*x*y + y >> 5*y*z ans = 5*y*(x^2 – 2*x*y + y) Variables and Assignments
You can solve equations involving variables with solve or fzero. >> solve(‘x^2 – 2*x – 4) ans = [ 5^(1/2) + 1] [ 1 – 5^(1/2)] You can specify more than one equation as well. >>[x, y]= solve(‘x^2–y = 2’,’y–2*x = 5’) x = [ 1 + 2*2^(1/2)] [ 1 – 2*2^(1/2)] y = [ 7 + 4*2^(1/2)] [ 7 – 4*2^(1/2)] Solving Equations
Vector A vector is an ordered list of numbers. You can enter a vector of any length in MATLAB by typing a list of numbers, separated by commas or space, inside square brackets. Ex) >> z = [ 2, 4, 6, 8 ] z = 2 4 6 8 >> x = 1 : 9 x = 1 2 3 4 5 6 7 8 9 >> x = 0 : 2 : 10 x = 0 2 4 6 8 10 Matrices A matrix is a rectangular array of numbers. Row and column vectors, which we discussed above, are examples of matrices. Ex) >>A=[1,2,3,4;5,6,7,8;9,10,11,12] A = 1 2 3 4 5 6 7 8 9 10 11 12 Vectors and Matrices
Built-in Functions MATLAB also has several built-in constants, including pi, I (the complex number) and inf(∞). Ex) >> log(exp(3)) ans = 3 >> sin(2*pi/3) ans = 0.8660 To get an exact answer, you need to use a symbolic argument: >> sin (sym (‘2*pi/3’) ) ans = 1/2*3^(1/2) User-Defined Functions In this section we will show how to use Inline to define your own functions. Ex) >> f = inline(‘x^2 + x + 1’, ‘x’) f = Inline function: f(x) = x^2 + x + 1 We conclude this section by remarking that one can also define functions of two or more variables: Ex) >> g = inline(‘u^2 + v^2’,‘u’,‘v’) g = inline function: g(u, v) = u^2 + v^2 Functions