100 likes | 220 Vues
This introductory guide explores the concept of functions in MATLAB, essential for scientific and engineering programming. It covers what a function is, its arguments (including arrays), and built-in functions like zeros, ones, eye, rand, and randn. The course also discusses polymorphism and keyboard input, highlighting the importance of user interfaces. It introduces formatted output with examples, and concludes with a section on plotting data using MATLAB. Examples illustrate how to create plots and visualize functions effectively.
E N D
Functions • What is a function? • In Math • In CS • Hundreds of Matlab Functions! • Input = Argument • Can we have more than one argument? • Can we have an array as a function argument? • Which functions have we used so far? • Find their arguments • Is ‘end’ a function?
Matrix building functions • zeros(n,m) Zeros • ones(n,m) Ones • eye(n,m) Zeros except that diagonal elements equal 1 • rand(n,m) Random numbers uniformly distributed in the range from 0 to 1 • randn(n,m) Random numbers normally distributed with mean equal to 0 and variance equal to 1
Polymorphism • Ex. sqrt • Scalar • Array • What does this mean? • Function call with multiple forms • Is it useful? • Another form: varying number of arguments • Ex. sum
Returning more than one objects • Array of objects • Ex. max
Keyboard input • What is a user interface? • Why do we need user input? • Where is the user input entered? • fave = input('Please type your favorite vector: '); • What will be the value of fave?
Formatted output • What is an output? • Why should we format our output? • Conversion and Escape characters • Ex. >> fprintf('No.: %d, cost= %5.2f.\nTotal is %7.3f\n', 4, 3.1, 4*3.1); No.: 4, cost= 3.10. Total is 12.400
Intro to plotting with Matlab If X is a 1-by-N (or N-by-1) vector, and Y is a 1-by-N (or N-by-1) vector, then >> plot(X,Y) creates a figure window, and plots the data in the axis. The points plotted are (X(1),Y(1)), (X(2),Y(2)), … , (X(N),Y(N)). By default, Matlab will draw straight lines between the data points, and the points will not be explicitly marked. For more info, do >> help plot Example: >> X = linspace(0,3*pi,1000); >> Y = sin(X); >> plot(X,Y)
Plotting several lines If X1 and Y1 are both 1-by-N, and X2 and Y2 are both 1-by-M, then >> plot(X1,Y1,X2,Y2) will plot both sets of data on the same axis. Example >> X1 = linspace(0,pi,1000); >> Y1 = cos(4*X1).*sin(X1); >> X2 = [0 1 4 5]; >> plot(X1,Y1,X2,sqrt(X2))