Programming in MATLAB ME 303. Outline of Lecture What is Matlab? Windows? Data Types –arrays: char, numeric, struct, cell Operators –arithmetic, relational,

Slides:



Advertisements
Similar presentations
Introduction to MATLAB
Advertisements

EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB.
Introduction to MATLAB
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Matlab intro The Environment
MATLAB Fundamentals.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
MATLAB Tutorials Session I Introduction to MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
Introduction to MATLAB
Introduction to MATLAB 58:111 Numerical Calculations Department of Mechanical and Industrial Engineering.
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
How to Use MATLAB A Brief Introduction. 2 What can MATLAB do? Matrix Operations Symbolic Computations Simulations Programming 2D/3D Visualization.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
Input, Output, and Processing
INTRODUCTION TO MATLAB LAB# 01
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (1): Introduction.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
MATLAB Practice 1 Introducing MATLAB Lecture Notes on Video Search & Mining, Spring 2012 Presented by Jun Hee Yoo Biointelligence Laboratory School of.
Basics of MATLAB By DR. Wafaa Shabana
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Matlab 14.html Cost: $100 Available in labs on Windows and Unix machines.
ES 240: Scientific and Engineering Computation. Chapter 2 Chapter 2: MATLAB Fundamentals Uchechukwu Ofoegbu Temple University.
Introduction to MATLAB. CSPP58001 MATLAB MATLAB is is a matrix-based language well suited for carrying out numerical analysis. It has many, many high-
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Master in Optical Fiber Communications and Photonic Technologies Foundations of Digital Transmission - Fall quarter Introduction to Matlab.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB Lecture 18.
INTRODUCTION TO MATLAB MATLAB is a software package for computation in engineering, science, and applied mathemat-ics. It offers a powerful programming.
A string is an array of characters Strings have many uses in MATLAB Display text output Specify formatting for plots Input arguments for some functions.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Tutorial 2 : Matlab - Getting Started.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Manipulating MATLAB Vector, Matrices 1. Variables and Arrays What are variables? You name the variables (as the programmer) and assign them numerical.
Introduction to MATLAB Ehsan Adeli M. Iran University of Science and Technology, E-Learing Center, Fall 2008 (1387)
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
1 Structured Programming EEN170 Programming in MATLAB.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
ECE 1304 Introduction to Electrical and Computer Engineering
Topics Designing a Program Input, Processing, and Output
MATLAB DENC 2533 ECADD LAB 9.
INTRODUCTION TO MATLAB
Topics Designing a Program Input, Processing, and Output
Experiment No. (1) - an introduction to MATLAB
Topics Designing a Program Input, Processing, and Output
Announcements P3 due today
How to Use MATLAB A Brief Introduction.
Presentation transcript:

Programming in MATLAB ME 303

Outline of Lecture What is Matlab? Windows? Data Types –arrays: char, numeric, struct, cell Operators –arithmetic, relational, logical Flow Control –conditionals, case, while, etc. M-functions –syntax –examples of simple functions –writing and debugging a simple MATLAB function

What is Matlab ? MATLAB® is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. This allows you to solve many technical computing problems, especially those with matrix and vector formulations, in a fraction of the time it would take to write a program in a scalar noninteractive language such as C or Fortran. So where other programming languages work with numbers one at a time, MATLAB allows you to work with entire matrices quickly and easily.FORTRAN: real*8 A(10,10), B(10,10), C(10,10) do i=1,10 do j=1,10 C(i,j) = A(i,j) + B(i,j) 10 continue 20 continue MATLAB: C = A + B The name MATLAB stands for matrix laboratory.

A software environment for interactive (No need to declare variables) numerical computations >> 2+3*4/2 >> a=5e-3; b=1; a+b Examples: –Matrix computations and linear algebra –Solving nonlinear equations –Numerical solution of differential equations –Mathematical optimization –Statistics and data analysis –Signal processing –Modelling of dynamical systems –Solving partial differential equations –Simulation of engineering systems What is Matlab ?

M-file editor/debugger window

Getting Help To get help: MATLAB main menu -> Help -> MATLAB Help

Type one of the following commands in the command window: –help – lists all the help topics –help topic – provides help for the specified topic –help command – provides help for the specified command –helpwin – opens a separate help window for navigation –Lookfor keyword – search all M-files for keyword Online resource( ) >> demo in matlab Getting Help

Variables Variable names: –Must start with a letter. –May contain only letters, digits, and the underscore “_”. –MATLAB is case sensitive, for example one & ONE are different variables. –MATLAB only recognizes the first 31 characters in a variable name. Assignment statement: –Variable = number; –Variable = expression; Example: >> t = 1234; –>> t = 1234 –t = – 1234

Variables Special variables: –ans: default variable name for the result. –pi: π = …… –eps: ε= e-016, smallest value by which two numbers can differ –inf: ∞, infinity –NAN or nan: not-a-number Commands involving variables: –who: lists the names of the defined variables –whos: lists the names and sizes of defined variables –clear: clears all variables –clear name: clears the variable name –clc: clears the command window –clf: clears the current figure and the graph window

Arrays A row vector in MATLAB can be created by an explicit list, starting with a left bracket, entering the values separated by spaces (or commas) and closing the vector with a right bracket. A column vector can be created the same way, and the rows are separated by semicolons. Example: –>> x = [ *pi 0.5*pi 0.75*pi pi] –x = x is a row vector. – –y=[0; 0.25*pi; 0.5*pi; 0.75*pi; pi] –y = y is a column vector. – 0 – – – –

Vector Addressing- A vector element is addressed in MATLAB with an integer index enclosed in parentheses. Example: –>> x(3) –ans = – <- 3rd element of vector X The colon notation may be used to address a block of elements (start:increment:end) Example: –>> x(1:2:5) –ans = – Arrays

Some useful commands: x = start:end Create row vector x starting with start, counting by 1, ending at end x = start:increment:end Create row vector x starting with start, counting by increment, ending at or before end x = linspace(start,end,number) Create linearly spaced row vector x starting with start, ending at end, having number elements x = logspace(start,end,number) Create logarithmically spaced row vector x starting with start, ending with end, having number elements length(x)Returns the length of vector x y = x’Transpose of vector x dot(x,y),cross(x,y) Returns the scalar dot and vector cross product of the vector x and y Arrays

Matrices A matrix –rectangular array of numbers –1-by-1 matrices, which are scalars, and –to matrices with only one row or column, which are vectors. –It begins with [, and end with ] –Spaces or commas are used to separate elements in a row –Semicolon or enter is used to separate rows A = [1,2,3;4,-5,6;5,-6,7] MATLAB has other ways of storing both numeric and nonnumeric data, but in the beginning, it is usually best to think of everything as a matrix.

Matrices Indexing Matrices Indexing using parentheses >> A(2,3) Index submatrices using vectors of row and column indices >> A([2 3],[1 2]) Ordering of indices is important! >> B=A([3 2],[2 1]) >> B=[A(3,2),A(3,1);A(2,2);A(2,1)]

Indexing Matrices Index complete row or column using the colon operator >> A(1,:) Can also add limit index range >> A(1:2,:) >> A([1 2],:) General notation for colon operator >> v=1:5 >> w=1:2:5 Matrices

Element-by-Element Array-Array Mathematics Example: >> x = [1 2 3]; >> y = [4 5 6]; >> z = x.* y z = operationAlgebraic FormMATLAB Additiona + b Subtractiona – b Multiplicationa x ba.* b Divisiona / ba./ b Exponentiationabab a.^ b Matrices

zeros(n)Returns a n X n matrix of zeros zeros(m,n)Returns a m X n matrix of zeros ones(n)Returns a n X n matrix of ones ones(m,n)Returns a m X n matrix of ones size(A) For a m X n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix length(A)Returns the larger of the number of rows or columns in A TransposeB=A’ Identity Matrix eye(n) -> returns an n X n identity matrix eye(m,n) -> returns an m X n matrix with ones on the main diagonal and zeros elsewhere Addition and SubtractionC =A +B C =A - B Scalar MultiplicationB = α A, where α is a scalar Matrix MultiplicationC = A * B Matrix InverseB = inv(A), A must be a square matrix in this case Matrix powersB = A * A, A must be a square matrix Determinantdet(A), A must be a square matrix

Expressions Numbers e e23 1i j 3e5i All numbers are stored internally using the long format. 16 significant decimal digits and a finite range of roughly to Variables S=5, Ali=6, a=4 A=3 a=? Functions Help elfun Help specfun Help elmat Variables are stored in the workspace who – list current variables whos – detailed list of variables clear – removes all variables from the workspace

Data Types in MATLAB

Uint8 and Doubles(Numeric) Double –almost all MATLAB functions expect doubles as arguments return doubles e.g., need to convert uint8 to double before performing any math operations » a = 1:10 a = » b = uint8(a) b = » whos Name Size Bytes Class a 1x10 80 double array b 1x10 10 uint8 array » b*2 ??? Error using ==> * Function '*' not defined for variables of class 'uint8'. » (double(b))*2 ans =

Char Data Type » c = ['hello']; » whos Name Size Bytes Class c 1x5 10 char array Grand total is 5 elements using 10 bytes » c(1) ans = h » d = [c,' again']; » d d = hello again » » b = ['hello';'again']; » size(b) ans = 2 5 » b b = hello again » name = 'Thomas R. Lee'; The class and ischar functions show name's identity as a character array: class(name) ans = char ischar(name) ans = 1

Structure Data Type image.name = 'Tom'; » image.height = 3; » image.width = 3; » image.data = [8 10 2; ; 2 4 7]; » whos Name Size Bytes Class image 1x1 590 struct array Grand total is 18 elements using 590 bytes >> image.name = 'Tom' image = name: 'Tom' >> image.height = 3; >> image.height = 3 image = name: 'Tom' height: 3 >> image.data = [8 10 2; ; 2 4 7] image = name: 'Tom' height: 3 data: [3x3 double] >> image.width = 3 image = name: 'Tom' height: 3 data: [3x3 double] width: 3 >> image image = name: 'Tom' height: 3 data: [3x3 double] width: 3

A cell array provides a storage mechanism for dissimilar kinds of data. You can store arrays of different types and/or sizes within the cells of a cell array. For example, you can store a 1-by-50 char array, a 7-by-13 double array, and a 1-by-1 uint32 in cells of the same cell array. To access data in a cell array, you use the same matrix indexing as with other MATLAB matrices and arrays. However, with cell array indexing, you use curly braces, {}, instead of square brackets an parentheses around the array indices. For example, A{2,5} accesses the cell in row 2 and column 5 of cell array A. Cell Arrays Data Type

Operators Arithmetic –numeric computations, e.g., 2^10 Relational –quantitative comparison of operands –e.g., a < b Logical –AND, OR, NOT –return Boolean variable, 1 (TRUE) or 0 (FALSE)

Arithmetic Operators Transpose, a’ Power, a^2 Addition, multiplication, division – a(1)*b(2) –a*b works if a and b are matrices with appropriate dimensions (columns(a) = rows(b)) –a.*b (element by element) except for matrix operations, most operands must be of the same size, unless one is a scalar

Arithmetic Operators Transpose, a’ Power, a^2 Addition, multiplication, division – a(1)*b(2) –a*b works if a and b are matrices with appropriate dimensions (columns(a) = rows(b)) –a.*b (element by element) except for matrix operations, operands must be of the same size, unless one is a scalar » a = [2 3]; » b = [4 5]; » a(1)*b(2) ans = 10 » a*b ??? Error using ==> * Inner matrix dimensions must agree. » a*b' ans = 23 » a.*b ans = 8 15 » b/2 ans =

Relational Operators, >=, ==, ~= compare corresponding elements of arrays with same dimensions if one is scalar, one is not, the scalar is compared with each element result is element by element, 1 or 0

Relational Operators, >=, ==, ~= compare corresponding elements of arrays with same dimensions if one is scalar, one is not, the scalar is compared with each element result is element by element 1 or 0 » a a = 2 3 » b b = 4 5 » a > b ans = 0 0 » b > a ans = 1 1 » a > 2 ans = 0 1

Logical Operators Logical operators (combinations of relational operators) &(and) |(or) ~(not) Logical functions xor isempty any all

Flow Control If –if logical_expression – statements –End if (beta(1)==0)&(alpha(1)~=0) K(1,1)=K(1,1)-(ko*beta(1)/alpha(1)); F(1)=F(1)-(ko*gama(1)/alpha(1)); end Else and elseif The else statement has no logical condition. The statements associated with it execute if the preceding if (and possibly elseif condition) is false (0). The elseif statement has a logical condition that it evaluates if the preceding if (and possibly elseif condition) is false (0). The statements associated with it execute if its logical condition is true (1). You can have multiple elseif statements within an if block. if n < 0 % If n negative, display error message. disp('Input must be positive'); elseif rem(n,2) == 0 % If n positive and even, divide by 2. A = n/2; else A = (n+1)/2; % If n positive and odd, increment and divide. end

Flow Control switch, case, and otherwise switch expression (scalar or string) case value1 statements % Executes if expression is value1 case value2 statements % Executes if expression is value2. otherwise statements % Executes if expression does not % match any case end switch input_num case -1 disp('negative one'); case 0 disp('zero'); case 1 disp('positive one'); otherwise disp('other value'); end

Flow Control Use the for statement to loop a specific number of times. The while statement is more suitable for basing the loop execution on how long a condition continues to be true or false. For for index = start:increment:end statements end for m = 1:5 for n = 1:100 A(m, n) = 1/(m + n - 1); end While while expression statements end while prod(1:n) < 1e100 n = n + 1; end

Continue The continue statement passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop. In nested loops, continue passes control to the next iteration of the for or while loop enclosing it. Flow Control fid = fopen('magic.m', 'r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) | strncmp(line, '%', 1) continue end count = count + 1; end disp(sprintf('%d lines', count));

Flow Control Break The break statement terminates the execution of a for loop or while loop. When a break statement is encountered, execution continues with the next statement outside of the loop. In nested loops, break exits from the innermost loop only fid = fopen('fft.m', 'r'); s = ''; while ~feof(fid) line = fgetl(fid); if isempty(line) break end s = strvcat(s, line); end disp(s)

a=input('a='); b=input('b='); c=input(‘please neter the value…’); input-output user_entry = input('prompt') displays prompt as a prompt on the screen, waits for input from the keyboard, and returns the value entered in user_entry. user_entry = input('prompt','s') returns the entered string as a text variable rather than as a variable name or numerical value reply = input('Do you want more? Y/N [Y]: ','s'); if isempty(reply) reply = 'Y'; end count = fprintf(fid,format,A,...) formats the data in the real part of matrix A (and in any additional matrix arguments) under control of the specified format string, and writes it to the file associated with file identifier fid. Fid is 1 for standard output (the screen) or 2 for standard error. The format argument is a string containing C language conversion specifications

input-output fprintf('A unit circle has circumference %g radians.\n',2*pi) A unit circle has circumference radians. B = [ ; ] fprintf(1,'X is %6.2f meters or %8.3f mm\n',9.9,9900,B) display the lines: X is 9.90 meters or mm X is 8.80 meters or mm X is 7.70 meters or mm

A,B,C Δ <0 ? Yes No A=0 ? No solution Yes No X1=….. X2=….. clear disp('This program is written... ') fprintf('\n') a=input('enter a='); while a==0 disp('a ya sifirdan farkli bir deger veriniz') a=input('Please re-enter the value of a='); end Delta=b^2-4*a*c; if Delta<0 ‘No solution’ else x1=(-b+sqrt(Delta))/(2*a); x2=(-b-sqrt(Delta))/(2*a); fprintf('First root=%5.5f \nSecond root=%5.5f',x1,x2) end

Plotting type help graph2d... Plotting a point: –>>plot (variablename, ‘symbol’) Example: Complex variable >>z = j; >>plot(z,‘*') Commands for axes: CommandDescription axis([xmin xmax ymin ymax])Define minimum and maximum values of the axes axis squareProduce a square plot axis equalEqual scaling factors for both axes axis normalTurn off axis square, equal axis (auto)Return the axis to defaults

Plotting Plotting curves: –plot(x,y) – generate a linear plot of the values of x (horizontal axis) and y (vertical axis) –semilogx(x,y) - generate a plot of the values of x (logarithmic scale) and y (linear scale) –semilogy(x,y) - –loglog(x,y) - generate a plot of the values of x and y (both logarithmic scale) Multiple curves –plot(x,y,w,z) – multiple curves can be plotted on the same graph: y vs. x and z vs. w –legend(‘string1’,’string2’, …) – used to distinguish between plots on the same graph Multiple figures –figure(n) – use in creation of multiple plot windows before the command plot() –close – closes the figure n window –close all – closes all the plot windows Subplots: –subplot(m,n,p) – m by n grid of windows, with p specifying the current plot as the pth window

Plotting Example: (polynomial function) –Plot the polynomial using linear/linear, log/linear, linear/log, log/log scale >>% generate te polynomial: >>x=linspace(0,10,100); >>y=2*x.^2+7*x+9; >>% plotting the polynomial: >>figure(1); >>subplot(2,2,1),plot(x,y); >>title('polynomial, linear/linear scale'); >>ylabel('y'),grid; >>subplot(2,2,2),semilogx(x,y); >>title('polynomial, log/linear scale'); >>ylabel('y'),grid; >>subplot(2,2,3),semilogy(x,y); >>title('polynomial, linear/log scale'); >>ylabel('y'),grid; >>subplot(2,2,4),loglog(x,y); >>title('polynomial, log/log scale'); >>ylabel('y'),grid;

Plotting Adding new curves to the exsiting graph Use the hold command to add lines/points to an existing plot –hold on – retain existing axes, add new curves to current axes. –hold off – release the current figure windows for new plots Grids and labels: CommandDescription grid onAdd dashed grids lines at the tick marks grid offRemoves grid lines (default) GridToggles grid status (off to on or on to off) title(‘text’)Labels top of plot with text xlabel(‘text’)Labels horizontal (x) axis with text ylabel(‘text’)Labels vertical (y) axis with text text(x,y,’text’)Adds text to location (x,y) on the current axes, where (x,y) is in units from the current plot

M-Files Before, we have executed the commands in the command window. The more general way is to create a M-file. The M-file is a text file that consists a group of MATLAB commands. MATLAB can open and execute the commands exactly as if they were entered at the MATLAB command window. To run the M-files, just type the file name in the command window. (make sure the current working directory is set correctly)

User Defined Function Add the following command in the beginning of your m-file: function [output variables] = function_name (input variables); –Note: the function_name should be the same as your file name to avoid confusion. Calling your function: –A user-defined function is called by the name of the m-file, not the name given in the function definition. –Type in the m-file name like other pre-defined commands. Comments: –The first few lines should be comments, as they will be displayed if help is requested for the function name. the first comment line is reference by the lookfor command.

Example ( circle1.m) function y = circle1(center,radius,nop,style) % circle1 draws a circle with center defined as a vector 'center' % radius as a scalar 'radius'. 'nop' is the number of points on the circle % 'style' is the style of the point. % Example to use: circle1([1 3],4,500, ':'); [m,n] = size(center); if (~((m == 1) | (n == 1)) | (m == 1 & n == 1)) error('Input must be a vector') end close all x0=center(1); y0=center(2); t0=2*pi/nop; axis equal axis([x0-radius-1 x0+radius+1 y0-radius-1 y0+radius+1]) hold on for i=1:nop+1 pos1=radius*cos(t0*(i-1))+x0; pos2=radius*sin(t0*(i-1))+y0; plot(pos1,pos2,style); end User Defined Function

In command window: –>> help circle1 –circle1 draws a circle with center defined as a vector 'center' radius as a scalar 'radius'. 'nop' is the number of points on the circle 'style' is the style of the point – Example to use: circle1([1 3],4,500,':'); Example: plot a circle with center (3,1), radius 5 using 500 points and style '--': –>> circle1([3 1],5,500,'--'); Result in the Figure window

References Matlab help 58:111 Numerical Calculations (Univ. Of Iowa) 2E1215 course of Mikael Johanson Dr. Ali A. JalaliMatlab Workshop of Dr. Ali A. Jalali Hakan Çopur’s Introductory Matlab PresentationHakan Çopur’s Introductory Matlab Presentation