This action might not be possible to undo. Are you sure you want to continue?

So You Think You Can

MATLAB

HANS-PETTER HALVORSEN, 2010.09.08

Part I: Introduction – MATLAB Basics

Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01

PREFACE

In this MATLAB Course you will learn basic MATLAB and how to use MATLAB in Control and Simulation applications. An introduction to Simulink and other Tools will also be given. MATLAB is a tool for technical computing, computation and visualization in an integrated environment. MATLAB is an abbreviation for MATrix LABoratory, so it is well suited for matrix manipulation and problem solving related to Linear Algebra, Modelling, Simulation and Control applications. This is a self-paced course based on this document and some short videos on the way. This document contains lots of examples and self-paced tasks that the users will go through and solve on their own. The user may go through the tasks in this document in their own pace and the instructor will be available for guidance throughout the course. The MATLAB Course consists of 3 parts (8 hours x 3): MATLAB Course – Part I: Introduction – MATLAB Basics MATLAB Course – Part II: Modelling, Simulation and Control MATLAB Course – Part III: Advanced Topics, Simulink and other Tools

In Part I of the course (Part I: Introduction – MATLAB Basics) you will be familiar with the MATLAB environment and learn basic MATLAB programming. The course consists of lots of Tasks you should solve while reading this course manual and watching the videos referred to in the text.

Make sure to bring your headphones for the videos in this course. The course consists of several short videos that will give you an introduction to the different topics in the course. What is MATLAB? MATLAB is a tool for technical computing, computation and visualization in an integrated environment. MATLAB is an abbreviation for MATrix LABoratory, so it is well suited for matrix manipulation and problem solving related to Linear Algebra. MATLAB is developed by The MathWorks. MATLAB is a short-term for MATrix LABoratory. MATLAB is in use world-wide by researchers and universities. For more information, see www.mathworks.com For more information about MATLAB, etc., please visit http://home.hit.no/~hansha/

ii

TABLE OF CONTENTS

Preface ..................................................................................................................................................................... ii Table of Contents .................................................................................................................................................... iii 1 2 Introduction....................................................................................................................................................1 The MATLAB Environment .............................................................................................................................2 2.1 2.2 2.3 2.4 2.5 3 4 Command Window .................................................................................................................................2 Command History ...................................................................................................................................3 Workspace ..............................................................................................................................................4 Current Directory....................................................................................................................................5 Editor ......................................................................................................................................................7

Using the Help System in MATLAB .................................................................................................................9 MATLAB Basics .............................................................................................................................................11 4.1 4.2 Basic Operations ...................................................................................................................................11 Arrays; Vectors and Matrices ...............................................................................................................15 Colon Notation .............................................................................................................................16

4.2.1 4.3

Tips and Tricks ......................................................................................................................................17 Array Operations..........................................................................................................................18

4.3.1 5

Linear Algebra; Vectors and Matrices ..........................................................................................................21 5.1 5.2 Vectors..................................................................................................................................................21 Matrices ................................................................................................................................................22 Transpose.....................................................................................................................................22 Diagonal .......................................................................................................................................23 Triangular .....................................................................................................................................24 Matrix Multiplication ...................................................................................................................24 Matrix Addition ............................................................................................................................25 Determinant .................................................................................................................................25 Inverse Matrices...........................................................................................................................26

5.2.1 5.2.2 5.2.3 5.2.4 5.2.5 5.2.6 5.2.7 5.3

Eigenvalues ...........................................................................................................................................27 iii

.....................................................................................................................................................................................................................................................................................................................58 10 Additional Tasks.............................................................................28 M files........2 9.................................................................................................................65 MATLAB Course .................45 If-else Statement ......................................................................................................................................................................................................1 6................2 8..........60 Appendix A: MATLAB Functions..........................................45 Switch and Case Statement ..................1 9..........................................................................................................................39 Custimizing ....................................................................................................................................6 Flow Control .....................................................3 9.............................................................................................................................................................44 8 Flow Control .....................................................2 7..............................................................................................................................................................................................................................49 While loop............47 For loop.............................................................................55 Polynomials............................................................................................................................51 9 Mathematics......................31 6........................................................1 8..........................53 9..................................36 7.....................................................................4 8.....53 Complex Numbers ............................................................................41 other Plots .................50 Additional Tasks ................................................................................................2 Scripts .....Part I: Introduction – MATLAB Basics .....................................................................................................1 7...............................................4 9...............................................3 7.33 7 Plotting .................4 6 Table of Contents Solving Linear Equations ................................................... Scripts and user-define functions ................53 Statistics ....................................................iv 5................38 Displaying Multiple Plots in One Figure – Sub-Plots ..........................................................................................5 8.........................................45 8...............................................................................................................................................3 8.....................................................................................31 Functions ...................................................................................................................................................................................................53 Trigonometric Functions.....................5 Basic Math Functions.................................................4 Plotting Multiple Data Sets in One Graph.

For and While Loops. Part I (8 hours): Introduction to MATLAB consists of the following: The MATLAB Environment Using the Help System in MATLAB MATLAB Basics Linear Algebra. http://home. If and Case statements Mathematics Additional Tasks 1 . web links.hit. documents. totally 8 hours x 3 = 24 hours.1 INTRODUCTION This Lab Work has its own web page with additional resources. etc. Vectors and Matrices M files. Scripts and User-defined functions Plotting Flow Control.no/~hansha/?lab=matlab This course contains of 3 parts of 8 hours each.

2 . you should watch the video “Working in the Development Environment”.hit.1 COMMAND WINDOW The Command window is the main window. The video is available from: http://home.no/~hansha/?lab=matlab [End of Task] 2. Use the Command Window to enter variables and to run functions and M-files scripts (more about m-files later).2 THE MATLAB ENVIRONMENT The MATLAB Environment consists of the following main parts: Command Window Command History Workspace Current Directory Editor Below we see the MATLAB environment: Task 1: Video Before you start.

for an example. You can also create an M-file from selected statements.3] If you.2. you can view and search for previously run statements.0 3] Or >> A = [1. e. defining the following matrix: The MATLAB syntax is as follows: >> A = [1 2.g.2 COMMAND HISTORY Statements you enter in the Command Window are logged in the Command History. want to find the answer to Type like this: >>a=4 >>b=3 >>a+b MATLAB then responds: ans = 7 2.. MATLAB Course .Part I: Introduction – MATLAB Basics .3 The MATLAB Environment You type all your commands after the command Prompt “>>”.0. as well as copy and execute selected statements. From the Command History.

4 The MATLAB Environment 2.Part I: Introduction – MATLAB Basics .3 WORKSPACE The Workspace window list all your variables used as long you have MATLAB opened. You could also use the following command >>who This command list all the commands used or MATLAB Course .

The command clear.Part I: Introduction – MATLAB Basics . MATLAB Course . will clear all the variables. this is useful if you want to save your data and use it for later. available in the current directory.mat file). dimensions. >>clear The MATLAB Environment Save your data: You may also save all your variables and data to a text file (. etc. etc.4 CURRENT DIRECTORY The “Current Directory” window lists all m files. Select the variables you want to save and right-click and select “Save As…”: MATLAB also have commands for this: save/load and diary. 2.5 >>whos This command lists all the command with the current values.

The Set Path dialog appears. see Figure below.6 The MATLAB Environment You should set your working folder as the Current Directory or set your working folder as part of the search path.Part I: Introduction – MATLAB Basics . if you don’t MATLAB will not find your files. Search Path: You set your search path from File→Set Path. MATLAB Course .

Click the “New M file” button in the Toolbar menu or File → New → M file.Part I: Introduction – MATLAB Basics . Below we see the Editor window: MATLAB Course .5 EDITOR The Editor is used to create scripts and m-files.7 The MATLAB Environment 2.

[End of Task] MATLAB Course .Part I: Introduction – MATLAB Basics . Task 2: MATLAB Environment Click around and make yourself familiar with the MATLAB Environment.8 The MATLAB Environment When you learn about m-files (scripts and functions) in a later chapter you will be using this editor.

From the menu: Help → MATLAB Help or use the Shortcut: F1 The following window appears: You may also type “Help” in the Command window: 9 . so make sure you are familiar with how the help system works.3 USING THE HELP SYSTEM IN MATLAB The Help system in MATLAB is quite comprehensive.

If you type “help <functionname>” you will get specific help about this function. You may also type more specific. You may also type “doc <topic>” to open the Help window on the specific topic of interest. and MATLAB will list all functions according to the specific category.10 Using the Help System in MATLAB MATLAB answers with links to lots of Help topics. Example: lookfor sine MATLAB Course . with a specific keyword you may use the lookfor command. “Help elfun” (Elementary Math Functions).Part I: Introduction – MATLAB Basics .g. e. etc.. Searching: We can use the help keyword when we want to get help for a specific function. but if we want to search for all functions.

4 MATLAB BASICS Task 3: Video Before you start. when you type a semicolon (.6097 3. Values can come from constants. Note! Unlike many other languages. MATLAB will not respond. >> a=5 a = 5 >> a=6.0000 1.no/~hansha/?lab=matlab [End of Task] 4. in MATLAB the semicolon serves to suppress the output of the line that it concludes. Example: >> x = 17 x = 17 >> x = 'hat' x = hat >> x = [3*4. MATLAB is dynamically typed. Some of them are explained here: 11 .) after the command.hit. meaning that variables can be assigned without declaring their type. and that their type can change.0000 [End of Example] Note! MATLAB is case sensitive! The variables x and X are not the same. “=”. >> As you see. from computation involving values of other variables. where the semicolon is used to terminate commands. you should watch the video “Getting Started with MATLAB” The video is available from: http://home. pi/2] x = 12.1 BASIC OPERATIONS Variables: Variables are defined with the assignment operator. or from the output of a function.5708 >> y = 3*sin(x) y = -1. Built-in constants: MATLAB have several built-in constants.

MATLAB allows you to reassign built-in function names as variable names. Infinity Not A Number. Example: MATLAB Course .. divide by zero.. e.12 Name i.g. you get NaN MATLAB Basics Naming a Variable Uniquely: To avoid choosing a name for a new variable that might conflict with a name already in use. >> iskeyword ans = 'break' 'case' 'catch' 'classdef' 'continue' 'else' 'elseif' 'end' 'for' 'function' 'global' 'if' 'otherwise' 'persistent' 'return' 'switch' 'try' 'while' You cannot assign these reserved names as your variable names.Part I: Introduction – MATLAB Basics . j pi inf NaN Description Used for complex numbers. If you. z=2+4i . check for any occurrences of the name using the which command: which Example: >> which -all pi built-in (C:\Matlab\R2007a\toolbox\matlab\elmat\pi) -all variablename You may also use the iskeyword command.g. e. but that is not recommended! – so be carefully when you select the name of your variables. This command causes MATLAB to list all reserved names.

Function help help <function> who. like disp. >>size(A) >>x=[1:1:10].y) >>cls Clear the Command window MATLAB Course . Size of arrays. >>length(x) >>A=[1 2. >>z=3. If you accidently do so. [End of Task] Built-in Functions: Here are some descriptions for the most used basic MATLAB functions. use the clear command to reset it back to normal. Other basic operations are: >>16-3 >>16/3 >>16*3 → Try them. [End of Example] MATLAB Basics Task 4: Basic Operations Type the following in the Command window: >>y=16. >>disp(A) >>x=[1:1:10]. etc. >>plot(x. >>y+z Note! When you use a semicolon. Note! Some functions display output even if you use semicolon.3 4]. matrices Length of a vector Set output format Display text or array This function is used to create a plot >>help >>help plot Example >>who >>whos >>clear >>clear x >>x=[1 2 .Part I: Introduction – MATLAB Basics . Clear variables and functions from memory.13 >> sin=4 sin = 4 >> sin(3) ??? Index exceeds matrix dimensions. whos clear size length format disp plot clc Description MATLAB displays the help information available Display help about a specific function who lists in alphabetical order all variables in the currently active workspace. >>plot(x) >>y=sin(x). plot. Try the code above with and without semicolon. 3 4]. no output will be displayed.

the mean and the standard deviation. Type “help <functionname>” in the Command window. you should use the Help system in MATLAB to read more about these functions.1) >>x=[1:1:10] >>max(x) >>x=[1:1:10] >>min(x) >>x=[1:1:10] >>mean(x) >>x=[1:1:10] >>std(x) MATLAB Basics Task 5: Help Before you start.14 rand max min mean std Creates a random number. vector or matrix Find the largest number in a vector Find the smallest number in a vector Average or mean value Standard deviation >>rand >>rand(2.Part I: Introduction – MATLAB Basics . Find the minimum value. [End of Task] MATLAB Course . the maximum value. [End of Task] Task 6: Statistics functions Create a random vector with 100 random numbers between 0 and 100.

1) ans = 1 3 or: MATLAB Course .” → To separate columns. you should watch the video “Working with Arrays”.” or a space “ “. 3. we can type like this: >> A(2. The video is available from: http://home.no/~hansha/?lab=matlab [End of Task] Matrices and vectors (Linear Algebra) are the basic elements in MathScript and also the basic elements in control design theory. So it is important you know how to handle vectors and matrices in MATLAB.Part I: Introduction – MATLAB Basics . VECTORS AND MATRICES Task 7: Video Before you start. we use a semicolon “. A general matrix A may be written like this: In MATLAB we type vectors and matrices like this: >> A=[1 2. 4] A = 1 2 3 4 → To separate rows. 3 4] A = 1 2 3 4 or: >> A=[1. 2. To get a specific part of a matrix.hit.2 ARRAYS.1) ans = 3 or: >> A(:. we use a comma “.15 MATLAB Basics 4.

16 >> A(2. MATLAB Course . >> B=[x y] B = 1 4 2 5 3 6 4.Part I: Introduction – MATLAB Basics . 5.1 COLON NOTATION The “colon notation” is very useful for creating vectors: Example: This example shows how to use the colon notation creating a vector and do some calculations.2. >> y=[4. 6].2.3].:) ans = 3 MATLAB Basics 4 From 2 vectors x and y we can create a matrix like this: >> x=[1.

3 TIPS AND TRICKS Naming conversions: MATLAB Course . [End of Task] Deleting Rows and Columns: You can delete rows and columns from a matrix using just a pair of square brackets []. >>A(:. -2 -3]. Example: Given To delete the second column of a matrix A.Part I: Introduction – MATLAB Basics . → Use MATLAB to find the second row of matrix C. use: >>A=[0 1.2) = [] A = 0 -2 [End of Example] 4. → Use MATLAB to find the third column of matrix C.17 MATLAB Basics Task 8: Vectors and Matrices Type the following vector in the Command window: Type the following matrix in the Command window: Type the following matrix in the Command window: → Use Use MATLAB to find the value in the second row and the third column of matrix C.

6 7 8 9 10] x = 1 2 3 . Example: >> x=1.z=3 x = 1 y = 2 z = 3 4. make sure you create a name that is not already exists in MATLAB..18 MATLAB Basics When creating variables and constants. you can use the “e” notation. e.y=2.. it may be difficult to fit one row on one command line. We may then split the row across several command lines by using the line continuation operator “. Use the which command to check if the name already exists: which –all <your name> Example: >> which -all sin built-in (C:\Matlab\R2007a\toolbox\matlab\elfun\@double\sin) built-in (C:\Matlab\R2007a\toolbox\matlab\elfun\@single\sin) Large or small numbers: If you need to write large or small numbers.Part I: Introduction – MATLAB Basics .5000e-008 Line Continuation: For large arrays. Example: >> x=[1 2 3 4 5 .”.. like >> 2e5 ans = 200000 >> 7.1 ARRAY OPERATIONS We have the following basic matrix operations: MATLAB Course .: % double method % single method 4 5 6 7 8 9 10 Multiple commands on same line: It is possible to type several commands on the same line..5e-8 ans = 7.3. Note also that MATLAB is case sensitive! The variables x and X are not the same.g. In some cases this is a good idea to save space.

19

MATLAB Basics

The basic matrix operations can be modified for element-by-element operations by preceding the operator with a period. The modified operations are known as array operations. Given

Then

The elements of A.*B are the products of the corresponding elements of A and B. We have the following array operators:

**Example: >> A=[1;2;3] A = 1 2 3 >> B=[-6;7;10] B = -6 7 10 >> A*B ??? Error using ==> mtimes Inner matrix dimensions must agree. >> A.*B ans = -6 14 30
**

MATLAB Course - Part I: Introduction – MATLAB Basics

20 [End of Example]

MATLAB Basics

MATLAB Course - Part I: Introduction – MATLAB Basics

5

LINEAR ALGEBRA; VECTORS AND MATRICES

Linear algebra is a branch of mathematics concerned with the study of matrices, vectors, vector spaces (also called linear spaces), linear maps (also called linear transformations), and systems of linear equations. MATLAB are well suited for Linear Algebra. This chapter assumes you have some basic understanding of Linear Algebra and matrices and vectors. Here are some useful functions for Linear Algebra in MATLAB: Function rank det inv eig ones eye diag Description

Find the rank of a matrix. Provides an estimate of the number of linearly independent rows or columns of a matrix A. Find the determinant of a square matrix Find the inverse of a square matrix Find the eigenvalues of a square matrix Creates an array or matrix with only ones Creates an identity matrix Find the diagonal elements in a matrix

Example

>>A=[1 2; 3 4] >>rank(A) >>A=[1 2; 3 4] >>det(A) >>A=[1 2; 3 4] >>inv(A) >>A=[1 2; 3 4] >>eig(A) >>ones(2) >>ones(2,1) >>eye(2) >>A=[1 2; 3 4] >>diag(A)

Type “help matfun” (Matrix functions - numerical linear algebra) in the Command Window for more information, or type “help elmat” (Elementary matrices and matrix manipulation). You may also type “help <functionname>” for help about a specific function.

Task 9: Help

Before you start, you should use the Help system in MATLAB to read more about these functions. Type “help <functionname>” in the Command window. [End of Task]

5.1

VECTORS

:

Given a vector

Example:

21

3] x = 1 2 3 The Transpose of vector x: Linear Algebra.-2 -3] A = 0 1 -2 -3 [End of Example] 5.Part I: Introduction – MATLAB Basics .2. Vectors and Matrices >> x' ans = 1 2 3 The Length of vector x: Orthogonality: [End of Example] 5.1 TRANSPOSE The Transpose of matrix A: Example: MATLAB Course . 2.2 MATRICES Given a matrix A: Example: >> A=[0 1.22 >> x=[1.

2.23 Linear Algebra.2 DIAGONAL The Diagonal elements of matrix A is the vector Example: >> diag(A) ans = 0 -3 [End of Example] The Diagonal matrix Λ is given by: Given the Identity matrix I: Example: >> eye(3) ans = 1 0 0 0 1 0 0 0 1 [End of Example] MATLAB Course .Part I: Introduction – MATLAB Basics . Vectors and Matrices >> A' ans = 0 1 -2 -3 [End of Example] 5.

4 MATRIX MULTIPLICATION Given the matrices and .2. Vectors and Matrices 5.3 -2] B = 1 0 3 -2 >> A*B ans = 3 -2 -11 6 → Check the answer by manually calculating using pen & paper. then where Example: >> A=[0 1.-2 -3] A = 0 1 -2 -3 >> B=[1 0.Part I: Introduction – MATLAB Basics . [End of Example] Note! Note! MATLAB Course .3 TRIANGULAR Lower Triangular matrix L: Upper Triangular matrix U: 5.2.24 Linear Algebra.

3 -2] >> A+B ans = 1 1 1 -5 → Check the answer by manually calculating using pen & paper.2. Vectors and Matrices 5.5 MATRIX ADDITION Given the matrices and . then the Determinant is given: Given a 2x2 matrix Then Example: A = 0 -2 1 -3 MATLAB Course .25 Linear Algebra.-2 -3] >> B=[1 0. then Example: >> A=[0 1.Part I: Introduction – MATLAB Basics .2. [End of Example] 5.6 DETERMINANT Given a matrix .

2. [End of Example] Linear Algebra.26 >> det(A) ans = 2 → Check the answer by manually calculating using pen & paper.Part I: Introduction – MATLAB Basics . Vectors and Matrices Notice that and Example: >> det(A*B) ans = -4 >> det(A)*det(B) ans = -4 >> det(A') ans = 2 >> det(A) ans = 2 [End of Example] 5.7 INVERSE MATRICES The inverse of a quadratic matrix is defined by: if For a 2x2 matrix we have: The inverse is given by MATLAB Course .

then the Eigenvalues is defined as: Example: A = 0 1 -2 -3 >> eig(A) ans = -1 -2 → Check the answer by manually calculating using pen & paper. [End of Example] Task 10: Matrix manipulation Given the matrix A.27 Example: A = 0 1 -2 -3 >> inv(A) ans = -1. Notice that: Linear Algebra. Vectors and Matrices [End of Example] 5.Part I: Introduction – MATLAB Basics .5000 1.0000 0 → Check the answer by manually calculating using pen & paper.5000 -0. B and C: → Solve the following basic matrix operations using MATLAB: MATLAB Course .3 Given EIGENVALUES .

using MATLAB. Solve the equations. diag = Diagonal. MATLAB Course . such as: LU factorization Singular value Decomposition Etc. [End of Task] When dealing with large matrices (finding inverse of A is time-consuming) or the inverse doesn’t exist other methods are used to find the solution. det = Determinant → Use MATLAB to prove the following: where is the unit matrix Linear Algebra. find .4 SOLVING LINEAR EQUATIONS Task 11: Linear Equations Given the equations: Set the equations on the following form: → Find A and b.e.Part I: Introduction – MATLAB Basics .28 where eig = Eigenvalues. Vectors and Matrices [End of Task] 5. i..

Part I: Introduction – MATLAB Basics . Task 13: Singular value Decomposition is given by The Singular value Decomposition (SVD) of the matrix where U is an orthogonal matrix MATLAB Course . Tip! Use the built-in lu function in MATLAB. Vectors and Matrices Task 12: LU Factorization is given by LU factorization of where L is a lower triangular matrix U is an upper triangular matrix → Find L and U using A found from the equations in the previous task.29 Linear Algebra. We have then that: Then we may solve by first solving with respect to Then solving with respect to [End of Task] using “back substitution”.

Tip! Use the built-in svd function in MATLAB. Vectors and Matrices Find U. S and V using matrix A from the previous task.30 V is an orthogonal matrix S is a diagonal singular matrix Linear Algebra.Part I: Introduction – MATLAB Basics . [End of Task] MATLAB Course .

m”. Create a new m-file from the File → New menu or the New button on the Toolbar. Save the file under a name that ends with “.6 M FILES. Task 14: Video Before you start. The built-in Editor for creating and modifying m-files are shown below: 31 .1 SCRIPTS A Script is a collection of MATLAB commands and functions that is bundled together in a m-file. The video is available from: http://home.no/~hansha/?lab=matlab [End of Task] 6. all the commands are executed. Use the MATLAB Editor or another text editor to create a file containing the same statements you would type at the MATLAB command line. When you run the Script.hit. you should watch the video “Writing a MATLAB Program”. SCRIPTS AND USER-DEFINE FUNCTIONS Scripts or m-files are text files containing MATLAB code.

32 M files. Scripts and user-define functions In the Editor you create a sequence of MATLAB commands that you save as a m-file (the file extension ends with .m). the button changes to “Run”. Push the “Save and Run” button when you want to run your program. If the code contains errors or warning the MATLAB compiler will let you know by display some colors symbols to the right in the Editor. An alternative is to type “Edit <m-file>” from the Command window. MATLAB Course . as shown on the Figure above.Part I: Introduction – MATLAB Basics . Running a m-file in the Command window (just type the name of the m-file and hit Enter to run the m-file): You may open or edit a m-file using the open button in the toolbar or the File→Open menu from MATLAB. Note! when you have saved the file.

To define your own function in MATLAB. You may use the function like this: MATLAB Course . [End of Task] 6.Part I: Introduction – MATLAB Basics .y) % this function add 2 numbers total = x+y. Scripts and user-define functions Task 15: Script Create a Script (M-file) where you create a vector with random data and find the average and the standard deviation Run the Script from the Command window. use the following syntax: function outputs = function_name(inputs) % documentation … Or in more detail: Note! It is recommended that you use lowercase in the function name Example: Here is a simple Example: function total = add(x.2 FUNCTIONS MATLAB includes more than 1000 built-in functions that you can use.33 M files. but sometimes you need to create your own functions.

b) [End of Example] M files. From the Command window you can then type “help <function name>” in order to read this information: >> help linsolution Solves the problem Ax=b using x=inv(A)*b Created By Hans-Petter Halvorsen [End of Example] MATLAB Course . b=6.b)) in the m. Scripts and user-define functions You may create your own functions and save them as a m-file. add(a.6].Part I: Introduction – MATLAB Basics .3) %Example 2: a=4.5000 After the function declaration (function [x] = linsolution(A. This is done with the Comment sign “%” before each line.file. you may write a description of the function.b). >> x = linsolution(A.0000 4. >> b=[5.3 4].34 %Example 1: add(2.b) x = -4. %Example 3: answer = add(a. Example: Create a function called “linsolution” which solve Below we see how the m-file for this function looks like: You may define A and b in the Command window and the use the function on order to find x: >> A=[1 2.

y) [End of Task] Task 17: User-defined function Create a function circle that finds the area in a circle based on the input parameter r (radius).Part I: Introduction – MATLAB Basics . >>z=calc_average(x.35 Naming a Function Uniquely: M files. Test the function afterwards as follows: >>x=2. [End of Task] MATLAB Course . >>y=4. Scripts and user-define functions To avoid choosing a name for a new function that might conflict with a name already in use. check for any occurrences of the name using this command: which -all functionname Task 16: User-defined function Create a function calc_average that finds the average of two numbers. Run and test the function in the Command window.

Task 19: Help Before you start. you should use the Help system in MATLAB to read more about these functions. >plot(X.7 PLOTTING Plotting is a very important and powerful feature in MATLAB.and y-axis of the current axes. Y) >>figure >>figure(1) >>subplot(2. “grid on” adds major grid lines to the current plot. breaks the Figure window into an m-by-n matrix of small axes. selects the p-th axes for the current plot.01:1]. etc. In this chapter we will learn the basic plotting functionality in MATLAB. you should watch the video “Visualization Data”.*X. then the second row.2. Create a new figure window Create subplots in a Figure.hit.no/~hansha/?lab=matlab [End of Task] Plots functions: Here are some useful functions for creating plots: Function plot figure subplot Description Generates a plot. >Y = X. Task 18: Video Before you start. Control axis scaling and appearance. “grid off” removes major and minor grid lines from the current plot. The video is available from: http://home.n.p) or subplot(mnp). Add title to current plot title('string') Add xlabel to current plot xlabel('string') Add ylabel to current plot ylabel('string') Creates a legend in the corner (or at a specified position) of the plot Freezes the current plot. subplot(m. plot(y) plots the columns of y against the indexes of the columns. or type “help <functionname>” for help about a specific function. “axis([xmin xmax ymin ymax])” sets the limits for the x.1) grid >>grid >>grid on >>grid off axis title xlabel ylabel legend hold >>axis([xmin xmax ymin ymax]) >>axis off >>axis on >>title('this is a title') >> xlabel('time') >> ylabel('temperature') >> legend('temperature') >>hold on >>hold off Type “help graphics” in the Command Window for more information. Creates grid lines in a plot. so that additional plots can be overlaid Example >X = [0:0. The axes are counted along the top row of the Figure window. [End of Task] 36 . Type “help <functionname>” in the Command window.

compute the output y as follows: >>y=cos(t).hit. The video is available from: http://home.1 seconds as follows: >>t=[0:0.1:10].no/~hansha/?lab=matlab [End of Task] Task 21: Plotting In the Command window in MATLAB window input the time from t=0 seconds to t=10 seconds in increments of 0. you should watch the video “Using Basic Plotting Functions”.Part I: Introduction – MATLAB Basics . Then.37 Example: Here we see some examples of how to use the different plot functions: Plotting [End of Example] Task 20: Video Before you start using these functions. MATLAB Course .

01:2*pi. y = sin(x).Part I: Introduction – MATLAB Basics .x. Example: x = 0:pi/100:2*pi. cos(x)) hold off This gives: MATLAB Course .y3) This gives: Another approach is to use the hold command: x=0:0.y2.y. plot(x.5).38 Use the Plot command: >>plot(t. y3 = sin(x-.1 PLOTTING MULTIPLE DATA SETS IN ONE GRAPH In MATLAB it is easy to plot multiple data set in one graph.25). y2 = sin(x-. sin(x)) hold on plot(x.x.y) [End of Task] Plotting 7. plot(x.

Part I: Introduction – MATLAB Basics .p)” partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. and so on.where is the time constant The solution for the differential equation is: Set and the initial condition in the time interval → Create a Script in MATLAB (.39 Plotting [End of Example] Task 22: Plot of dynamic system Given the autonomous system: where . then the second row. MATLAB Course .2 DISPLAYING MULTIPLE PLOTS IN ONE FIGURE – SUB-PLOTS The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper. Typing “subplot(m. [End of Task] 7. and proper Title and Axis Labels to the plot. The plots are numbered along the first row of the figure window.m file) where you plot the solution → Add Grid.n.

2.Z) This gives: [End of Example] MATLAB Course .2.Z] = cylinder(4*cos(t)).Y.4).2.Part I: Introduction – MATLAB Basics .2). subplot(2.n.3).2. mesh(Z) subplot(2. mesh(Y) subplot(2. mesh(X.40 Plotting The syntax is as follows: subplot(m.p) Example: t = 0:pi/10:2*pi. [X.Y. mesh(X) subplot(2.1).

3 CUSTIMIZING There is lots of customizing you can do with plots. ylabel.Part I: Introduction – MATLAB Basics .41 Plotting Task 23: Sub-plots Plot Sin(x) and Cos(x) in 2 different subplots. legend. plot(x. etc.and y-axis labels. sin(x)) %Customize the Plot: title('This is a Title') xlabel('This is a X label') ylabel('This is a y label') legend('sin(x)') grid on This gives the following plot: MATLAB Course . Example: x=0:0. Add Titles and Labels.. The functions for doing this is. [End of Task] 7. e. add a legend and customize line colors and line-styles. xlabel. x. title. you can add a title.1:2*pi.g.

42 [End of Example] Plotting For line colors and line-styles we have the following properties we can use for the plot function: Line Styles: Marker specifiers: Colors: MATLAB Course .Part I: Introduction – MATLAB Basics .

1:2*pi. 'r:o') This gives the following plot: [End of Example] MATLAB Course . >> plot(x.43 Plotting Example: >> x=0:0. sin(x).Part I: Introduction – MATLAB Basics .

semilogy. fill. polar. semilogx. → Try some of them. Task 24: Other Plots Check out the help for the following 2D functions in MATLAB: loglog. [End of Task] MATLAB Course . scatter.44 Plotting 7. bar.g. hist.Part I: Introduction – MATLAB Basics . barh.. e. hist and pie. plotyy. pie. area. errorbar. fplot.4 OTHER PLOTS MATLAB offers lots of different plots. bar.

terminates the last group of statements. An end keyword. The optional elseif and else keywords provide for the execution of alternate groups of statements.1 FLOW CONTROL FLOW CONTROL You may use different loops in MATLAB For loop While loop If you want to control the flow in your program.2 IF-ELSE STATEMENT The if statement evaluates a logical expression and executes a group of statements when the expression is true. The general syntax is as follows: if expression1 statements1 elseif expression2 statements2 else statements3 end Example: n=5 if n > 2 M = eye(n) elseif n < 2 M = zeros(n) else M = ones(n) end or: n=5 if n == 5 M = eye(n) 45 . The groups of statements are delineated by the four keywords—no braces or brackets are involved. which matches the if. you may want to use one of the following: If-else statement Switch and case statement 8.8 8.

. → Try it! [End of Example] Operators: You may use the following operators in MATLAB: Mathematical Operator Description Less Than Less Than or Equal To Greater Than Greater Than or Equal To Equal To Not Equal To MATLAB Operator < <= > >= == ~= Logical Operators: You may use the following logical operators in MATLAB: Logical Operator AND OR MATLAB Operator & | Task 25: If-else Statements Given the second order algebraic equation: MATLAB Course ..Part I: Introduction – MATLAB Basics .. Note! If A and B are scalars this works – but If A and B are matrices this might not work as expected! → Try it! Use instead: if isequal(A.46 else M = ones(n) end Note! You have to use “if n == 5” – not ”if n = 5” [End of Example] Flow Control Example: if A == B. ... B).

c) … → Use if-else statements to solve the problems → Test the function from the Command window to make sure it works as expected.g. e.Part I: Introduction – MATLAB Basics .47 The solution (roots) is as follows: Flow Control where .b.any complex number is a solution → Create a function that finds the solution for x based on different input values for a. The general syntax is as follows: MATLAB Course .c) [End of Task] 8. function x = solveeq(a. There must always be an end to match the switch.c=1 >> solveeq(a. b and c. The keywords case and otherwise delineate the groups. e..b. b=2. >> a=0.3 SWITCH AND CASE STATEMENT The switch statement executes groups of statements based on the value of a variable or expression. .there is no solution.. Only the first matching case is executed.g.

48 Flow Control switch variable case case_value1 statements1 case case_value2 statements2 … otherwise statements end Example: n=2 switch(n) case 1 M = eye(n) case 2 M = zeros(n) case 3 M = ones(n) end [End of Example] Task 26: Switch-Case Statements Create a function that finds either the Area or the circumference of a circle using a Switch-Case statement You can.g.1) % 1 means area >> calccircl(r. >> calccircl(r. call the function like this: >> r=2.. e.Part I: Introduction – MATLAB Basics .2) % 2 means circumference [End of Task] Task 27: Switch-Case Statements Given the second order algebraic equation: MATLAB Course .

b=2. The general syntax is as follows: for variable = initval:endval statement . function x = solveeq2(a.c=1 >> solveeq2(a.c) … → Try to use a Switch-Case statements to solve the problem → Test the function from the Command window to make sure it works as expected. b and c.. statement end Example: m=5 for n = 1:m r(n) = rank(magic(n)). MATLAB Course . e..any complex number is a solution → Create a function that finds the solution for x based on different input values for a.there is no solution.4 FOR LOOP The For loop repeats a group of statements a fixed.g.Part I: Introduction – MATLAB Basics ..b.. >> a=0.49 Flow Control The solution (roots) is as follows: where .b. predetermined number of times. A matching end delineates the statements.g. .c) [End of Task] 8. e.

arrangement of leaves on a stem. … By definition.5 WHILE LOOP MATLAB Course . >> N=10. and are used in computer algorithms such as the Fibonacci search technique and the Fibonacci heap data structure. 89. 13. They also appear in biological settings. the fruitlets of a pineapple. [End of Task] 8. 144. the sequence Fn of Fibonacci numbers is defined by the recurrence relation: with seed values: → Write a function in MATLAB that calculates the N first Fibonacci numbers. the first two Fibonacci numbers are 0 and 1. In mathematical terms. Some sources omit the initial 0. such as branching in trees.g. 21.3.50 end r [End of Example] Flow Control Task 28: Fibonacci Numbers In mathematics. >> fibonacci(N) ans = 0 1 1 2 3 5 8 13 21 34 → Use a For loop to solve the problem. e. 55. 1. in strategies such as Fibonacci retracement. 5. an uncurling fern and the arrangement of a pine cone. Fibonacci numbers are used in the analysis of financial markets.. 34. 8.Part I: Introduction – MATLAB Basics . the flowering of artichoke. instead beginning the sequence with two 1s. 1. and each subsequent number is the sum of the previous two. 2 . Fibonacci numbers are the numbers in the following sequence: 0.

[End of Task] 8.Part I: Introduction – MATLAB Basics . zeros(m) end [End of Example] Task 29: While Loop Create a Script or Function that creates Fibonacci Numbers up to a given number. Use a For loop to iterate through the values in the vector and find sum in each iteration: mysum = mysum + x(i). Task 30: For Loops Extend your calc_average function from a previous task so it can calculate the average of a vector with random elements. The general syntax is as follows: while expression statements end Example: m=5. while m > 1 m = m .6 ADDITIONAL TASKS Here are some additional tasks about Loops and Flow control.g. A matching end delineates the statements.51 Flow Control The while loop repeats a group of statements an indefinite number of times under control of a logical condition. >> maxnumber=2000. e. >> fibonacci(maxnumber) Use a While Loop to solve the problem.1. Test the function in the Command window [End of Task] MATLAB Course ..

discard these values from the calculated average.Part I: Introduction – MATLAB Basics .52 Flow Control Task 31: If-else Statement Create a function where you use the “if-else” statement to find elements larger then a specific value in the task above. Example discarding numbers larger than 10 gives: x = 4 6 12 >> calc_average3(x) ans = 5 [End of Task] MATLAB Course . If this is the case.

etc. cos. Note! Most of the trigonometric functions require that the angle is expressed in radians.2 STATISTICS Some Statistics functions in MATLAB: mean. → Look up these functions in the Help system in MATLAB.g. Example: >> sin(pi/4) ans = 0. etc. maximum and the variance. min. minimum. sqrt. [End of Task] 9.. sin. 9. e. → Look up these functions in the Help system in MATLAB. max.9 MATHEMATICS MATLAB is a powerful tool for mathematical calculations. std. tan. median.1 BASIC MATH FUNCTIONS Some Basic Math functions in MATLAB: exp.7071 53 . etc. Type “help elfun” (elementary functions) in the Command window for more information about basic mathematical functions. standard deviation.3 TRIGONOMETRIC FUNCTIONS MATLAB offers lots of Trigonometric functions. Task 33: Statistics Create a vector with random numbers between 0 and 100. Task 32: Basic Math function Create a function that calculates the following mathematical expression: [End of Task] 9. Find the following statistics: mean.→ Look up these functions in the Help system in MATLAB. log.

We have that: This gives: → Create two functions that convert from radians to degrees (r2d(x)) and from degrees to radians (d2r(x)) respectively. (b.Part I: Introduction – MATLAB Basics .c) and (a. a third input “type” to define the different types above.. Test the functions to make sure it works properly. [End of Task] MATLAB Course . Test the functions to make sure that they work as expected. e.g.54 [End of Example] Mathematics Task 34: Conversion It is quite easy to convert from radians to degrees or from degrees to radians. → Use you previous function r2d() to make sure the output of your function is in degrees and not in radians.b) respectively. [End of Task] Task 35: Trigonometric functions on right triangle Given right triangle: → Create a function that finds the angle A (in degrees) based on input arguments (a.c). Use.

Part I: Introduction – MATLAB Basics .55 Mathematics Task 36: Given: Law of cosines Create a function where you find c using the law of cosines.4 COMPLEX NUMBERS Complex numbers are important in modelling and control theory. and use different line styles and colors for the plots. A complex number is defined like this: or The imaginary unit or is defined as: a is called the real part of z and b is called the imaginary part of z MATLAB Course . Make sure to add labels and a legend. [End of Task] Task 37: Plot and Plotting for in the same plot. [End of Task] 9. Test the functions to make sure it works properly.

we use the polar form.56 Re(z)=a. MATLAB Course .Part I: Introduction – MATLAB Basics . Im(z)=b You may also imaginary numbers on exponential/polar form: Mathematics where: Note that and Rectangular form of a complex number Example: Given the following complex number: Exponential/polar form of a complex number In MATLAB we may type: >> z=2+3i or: >> z=2+3j [End of Example] The complex conjugate of z is defined as: To add or subtract two complex numbers. In Division and multiplication. we simply add (or subtract) their real parts and their imaginary parts.

imag. conj(x) is the complex conjugate of x.57 Given the complex numbers: and Multiplication: Mathematics Division: MATLAB functions: Some Basic functions for complex numbers in MATLAB: abs. imag(z) is the imaginary part of z.Part I: Introduction – MATLAB Basics . etc. Function i. conj. real. real(z) is the real part of z. Complex conjugate.b) returns the complex result A + Bi >>z=2+4i >>z=2+4j Example abs angle imag real conj complex >>z=2+4i >>abs(z) >>z=2+4i >>angle(z) >>z=2+4i >>b=imag(z) >>z=2+4i >>a=real(z) >>z=2+4i >>z_con=conj(z) >>a=2. MATLAB Course . imag. the expressions 3+2i. Phase angle. Complex real part. 3+2*i. etc. As the basic imaginary unit SQRT(-1). angle(z) returns the phase angles. For example.b) Look up these functions in the Help system in MATLAB. c = complex(a. → Use MATLAB to find . abs(x) is the absolute value of the elements of x. in radians Complex imaginary part. together with the formulas for complex numbers that are listed above in the text (as you do it when you should calculate it using pen & paper). angle. >>b=3. Task 38: Complex numbers Given two complex numbers Find the real and imaginary part of c and d in MATLAB. 3+2j. i and j are used to enter complex numbers. When x is complex. real. 3+2*j and 3+2*sqrt(-1) all have the same value. complex. abs(x) is the complex modulus (magnitude) of the elements of X. complex. Use the direct method supported by MATLAB and the specific complex functions abs. conj.j Description Imaginary unit. Construct complex result from real and imaginary parts. angle. >>z=complex(a.

Part I: Introduction – MATLAB Basics . Task 39: Complex numbers Find the roots of the equation: Discuss the results.45 0 3.58 Mathematics → Find also [End of Task] and . deconv. → Look up these functions in the Help system in MATLAB. polyder. [End of Task] 9.4500 0 3. Find also the complex conjugate. MATLAB represents polynomials as row arrays containing coefficients ordered by descending powers.0000 5. roots. polyint.8] p = -5.8000 Task 40: Polynomials Define the following polynomial in MATLAB: MATLAB Course . Add the sum of the roots. Example: Given the polynomial: In MATLAB we write: >> p=[-5. 8.5 POLYNOMIALS A polynomial is expressed as: where are the coefficients of the polynomial. polyval. polyfit. such as conv.2 8 5.2000 [End of Example] MATLAB offers lots of functions on polynomials. etc.

e. [End of Task] ) using MATLAB and find the roots . [End of Task] MATLAB Course .order Polynomial that best fits the following function: Use the polynomial functions listed above.. → Plot both the function and the 6. order Polynomial to compare the results. Task 42: Polynomial Fitting Find the 6.59 Mathematics → Find the roots of the polynomial ( → Find Use the polynomial functions listed above.Part I: Introduction – MATLAB Basics . [End of Task] ) Task 41: Polynomials Given the following polynomials: → Find the polynomial → Find the roots of the polynomial ( → Find → Find the differentiation/derivative of Use the polynomial functions listed above. i.

g. solve the tasks below.: function h = pyt(a. → How many years will it take to convert all the mass of the sun completely? Do we need to worry if the sun will be used up in our generation or the next? The mass of the sun is [End of Task] Task 45: Cylinder surface area 60 . [End of Task] Task 44: MATLAB Script Given the famous equation from Albert Einstein: The sun radiates of energy per day..b) % . e. → Calculate how much of the mass on the sun is used to create this energy per day.10 ADDITIONAL TASKS If you have time left or need more practice. Task 43: User-defined function Create a function that uses Pythagoras to calculate the hypotenuse of a right-angled triangle. … h = … Pythagoras theorem is as follows: Note! The function should handle that a and b could be vectors.

[End of Task] Task 46: Create advanced expressions in MATLAB Create the following expression in MATLAB: Given → Find (The answer should be ) Tip! You should split the expressions into different parts. such as: poly = num =… den =…. and you minimize the risk of making an error while typing the expression in MATLAB.Part I: Introduction – MATLAB Basics .61 Additional Tasks Create a function that finds the surface area of a cylinder based on the height (h) and the radius (r) of the cylinder. f =… This makes the expression simpler to read and understand. [End of Task] MATLAB Course .

for t=1:tmax y(t. % preallocating for t=1:tmax y(t. We will use the functions tic and toc to find the execution time.1)=cos(t). We will create a simple program that calculates Create the following Script: % Test 1: Using a For Loop clear tic tmax=100000. end toc → What was the execution time? MATLAB Course .1). end toc → What was the execution time? for t=1 to 100 000.Part I: Introduction – MATLAB Basics .62 Additional Tasks Task 47: Solving Equations Find the solution(s) for the given equations: [End of Task] Task 48: Preallocating of variables and vectorization Here we will use preallocating of variables and vectorization and compare with using a For Loop.1)=cos(t). y=zeros(tmax. We will improve the Script by preallocating space for the variable y. Create the following Script: % Test 2: For Lopp with preallocating clear tic tmax=100000.

63 We will improve the Script further by removing the For Loop by using vectorization instead: % Test 3: Vectorization clear tic tmax=100000. MATLAB Course .-2 -3] A = 0 1 -2 -3 >> B=[1 0.Part I: Introduction – MATLAB Basics .B) … Tip! You need to use 3 nested For Loops. %vectorization y=cos(t). [End of Task] Additional Tasks Task 49: Nested For Loops and . toc → What was the execution time? Discuss the result. t=1:tmax.3 -2] B = 1 0 3 -2 >> A*B ans = 3 -2 -11 6 But her you will create your own function that multiply two matrices: function C = matrixmult(A. then Given the matrices where In MATLAB it is easy to multiply two matrices: >> A=[0 1.

64 [End of Task] Additional Tasks MATLAB Course .Part I: Introduction – MATLAB Basics .

Some of them are explained here: Name i. whos clear size length format disp plot clc rand max min mean std Description MATLAB displays the help information available Display help about a specific function who lists in alphabetical order all variables in the currently active workspace. Clear variables and functions from memory. 3 4] >>det(A) >>A=[1 2.3 4]. Provides an estimate of the number of linearly independent rows or columns of a matrix A. Find the determinant of a square matrix Find the inverse of a square matrix Find the eigenvalues of a square matrix Creates an array or matrix with only ones Creates an identity matrix Example >>A=[1 2. Size of arrays. Function help help <function> who. 3 4] >>eig(A) >>ones(2) >>ones(2. e. >>disp(A) >>x=[1:1:10]. >>plot(x..1) >>eye(2) 65 . >>length(x) >>A=[1 2.1) >>x=[1:1:10] >>max(x) >>x=[1:1:10] >>min(x) >>x=[1:1:10] >>mean(x) >>x=[1:1:10] >>std(x) Clear the Command window Creates a random number. >>plot(x) >>y=sin(x). If you. you get NaN Example >>who >>whos >>clear >>clear x >>x=[1 2 .APPENDIX A: MATLAB FUNCTIONS Built-in constants: MATLAB have several built-in constants.g. Infinity Not A Number. vector or matrix Find the largest number in a vector Find the smallest number in a vector Average or mean value Standard deviation Linear Algebra: Here are some useful functions for Linear Algebra in MATLAB: Function rank det inv eig ones eye Description Find the rank of a matrix..g. 3 4] >>inv(A) >>A=[1 2. divide by zero.y) >>cls >>rand >>rand(2. e. matrices Length of a vector Set output format Display text or array This function is used to create a plot >>help >>help plot Description Used for complex numbers. j pi inf NaN Basic Functions: Here are some descriptions for the most used basic MATLAB functions. 3 4]. z=2+4i . 3 4] >>rank(A) >>A=[1 2. >>size(A) >>x=[1:1:10].

3 4] >>diag(A) Type “help matfun” (Matrix functions .1) grid >>grid >>grid on >>grid off axis title xlabel ylabel legend hold >>axis([xmin xmax ymin ymax]) >>axis off >>axis on >>title('this is a title') >> xlabel('time') >> ylabel('temperature') >> legend('temperature') >>hold on >>hold off Type “help graphics” in the Command Window for more information. or type “help elmat” (Elementary matrices and matrix manipulation).n. “grid off” removes major and minor grid lines from the current plot. >Y = X. Plotting: Plots functions: Here are some useful functions for creating plots: Function plot figure subplot Description Generates a plot. The axes are counted along the top row of the Figure window. “axis([xmin xmax ymin ymax])” sets the limits for the x.numerical linear algebra) in the Command Window for more information.66 diag Find the diagonal elements in a matrix Appendix A: MATLAB Functions >>A=[1 2. Creates grid lines in a plot. etc. breaks the Figure window into an m-by-n matrix of small axes.2. >plot(X.and y-axis of the current axes. so that additional plots can be overlaid Example >X = [0:0.Part I: Introduction – MATLAB Basics MATLAB Operator < <= > >= == ~= . “grid on” adds major grid lines to the current plot.*X. Create a new figure window Create subplots in a Figure.01:1]. Control axis scaling and appearance. selects the p-th axes for the current plot. Operators: You may use the following operators in MATLAB: Mathematical Operator Description Less Than Less Than or Equal To Greater Than Greater Than or Equal To Equal To Not Equal To Logical Operators: You may use the following logical operators in MATLAB: MATLAB Course . then the second row. Add title to current plot title('string') Add xlabel to current plot xlabel('string') Add ylabel to current plot ylabel('string') Creates a legend in the corner (or at a specified position) of the plot Freezes the current plot. or type “help <functionname>” for help about a specific function. plot(y) plots the columns of y against the indexes of the columns.p) or subplot(mnp). Y) >>figure >>figure(1) >>subplot(2. subplot(m. You may also type “help <functionname>” for help about a specific function.

>>b=3.67 Logical Operator AND OR MATLAB Operator & | Appendix A: MATLAB Functions Complex Numbers: Functions used to create or manipulate complex numbers.b) MATLAB Course .j Description Imaginary unit. abs(x) is the complex modulus (magnitude) of the elements of X. imag(z) is the imaginary part of z. conj(x) is the complex conjugate of x. the expressions 3+2i. i and j are used to enter complex numbers. 3+2*i. 3+2j. Complex real part.Part I: Introduction – MATLAB Basics . Phase angle. 3+2*j and 3+2*sqrt(-1) all have the same value. angle(z) returns the phase angles. Function i. c = complex(a. Construct complex result from real and imaginary parts.b) returns the complex result A + Bi >>z=2+4i >>z=2+4j Example abs angle imag real conj complex >>z=2+4i >>abs(z) >>z=2+4i >>angle(z) >>z=2+4i >>b=imag(z) >>z=2+4i >>a=real(z) >>z=2+4i >>z_con=conj(z) >>a=2. Complex conjugate. For example. abs(x) is the absolute value of the elements of x. When x is complex. >>z=complex(a. As the basic imaginary unit SQRT(-1). real(z) is the real part of z. in radians Complex imaginary part.

p.hit.no Hans-Petter Halvorsen. Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.Sc. M.halvorsen@hit.hit. Telemark University College Department of Electrical Engineering.no/~hansha/ Room: B-237a .Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn. Norway www.no Blog: http://home.

Sign up to vote on this title

UsefulNot useful- Matlab Lichti
- MATLAB
- Lab0
- Print Able
- Tutorial Mathlab
- Partial Differential Equations
- Matlab Tutorial
- M-Slides
- Matlab Basics
- Learn MATLAB
- L17_matlab uses for image
- 6 5-Modelling Simulation MATLAB Primer_WS-06 5_2 Days
- Matlab Probs2
- Matlab Training - Writing M-files_scripts and Functions
- MATlab
- cs377s-Jan17_2
- MATLAB Preparation Document UIT
- New Microsoft Word Document
- 01_Introduction to MATLAB
- Mc Toolbox
- Mat Lab for Sci Lab Users
- 2011-The Matlab Reservoir Simulation Toolbox
- EE computer application
- lapskimik
- Chapter 3 New
- Trabajo de Electronica
- fdi_2009_matlab
- Fdi 2009 Matlab
- MATPOWER-OPF-slides.pdf
- My Matlab3
- MATLAB Course - Part 1