63
BASIC SIMULATION LAB FILE (4MAE5-Y) Submitted By: Submitted To: Keshav Poddar Mr. Devesh Kumar (A2325313006) (Assistant Professor) 4MAE-5(Y)

Basic Simulation Lab File

  • Upload
    bharat

  • View
    1.143

  • Download
    140

Embed Size (px)

DESCRIPTION

simulation lab(matlab)

Citation preview

BASIC SIMULATION LAB FILE (4MAE5-Y)

Submitted By: Submitted To:

Keshav Poddar Mr. Devesh Kumar(A2325313006) (Assistant Professor)4MAE-5(Y)

TABLE OF CONTENTSS.NO.TITLE OF THE EXPERIMENTS DATE OF EXPERIMENTDATE OF SUBMISSION

1.Creating a One and Two- Dimensional Array (Row / Column Vector) (Matrix of given size) then,(A). Performing Arithmetic Operations -Addition, Subtraction, Multiplication and Exponentiation.(B). Performing Matrix operations -Inverse, Transpose, Rank with PLOTS

2.Performing Matrix Manipulations -Concatenating, Indexing, Sorting, Shifting, Reshaping, Resizing and Flipping about a Vertical Axis / Horizontal Axis; Creating Arrays X & Y of given size (1 x N) and Performing(A). Relational Operations ->, 100.Exercise: Testing the Scripts written using A). T = 5, h = -5and B). T = 110, h =949.5

9.Generating a Square Wave from sum of Sine Waves of certain Amplitude and Frequencies.

10.Basic 2D and 3D plots: parametric space curve.polygons with vertices. 3D contour lines, pie and bar charts

EXPERIMENT:1

AIM: Creating a One-Dimensional Array (Row / Column Vector), Creating a Two-Dimensional Array (Matrix of given size) and (A). Performing Arithmetic Operations - Addition, Subtraction, Multiplication and Exponentiation. (B). Performing Matrix operations - Inverse, Transpose, Rank.

TOOL USED: MATLAB 7.0

THEORY:

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. Typical uses include Math and computation, Algorithm development, Data acquisition, Modeling, simulation, and prototyping, Data analysis, exploration, and visualization, Scientific and engineering graphics, Application development, including graphical user interface building.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 SUGGESTED PROGRAM: in a scalar non interactive language such as C or Fortran. The name MATLAB stands for matrix laboratory.Matrix Addition and Subtraction is performed by merely adding or subtracting the matrix elements by their corresponding elements in the other matrix.Consider two matrices A and B. If A is an m x n matrix and B is an n x p matrix, they could be multiplied together to produce an m x n matrix C. Matrix multiplication is possible only if the number of columns n in A is equal to the number of rows n in B. In matrix multiplication, the elements of the rows in the first matrix are multiplied with corresponding columns in the second matrix. Each element in the (i, j)thposition, in the resulting matrix C, is the summation of the products of elements in ithrow of first matrix with the corresponding element in the jthcolumn of the second matrix. In MATLAB, matrix multiplication is performed by using the * operator.The inverse of a matrix does not always exist.If the determinant of the matrix is zero, then the inverse does not exist and the matrix is singular.

Inverse of a matrix A is given by inv(A).

Transpose operation switches the rows and columns in a matrix. It is represented by a single quote(').Rank function provides an estimate of the number of linearly independent rows or columns of a null matrix.k = rank(A) returns the number of singular values of A that are larger than the default tolerance, max(size(A))*eps(norm(A)).k = rank(A,tol) returns the number of singular values of A that are larger than tol.MATLAB PROGRAM:-

%creating one dimensional row matrix of order 1*3%a=[2,3,4];b=[6,7,5];%creating one dimensional column matrix of order 3*1%c=[3;4;5];d=[5;9;8];%creating two dimensional row matrix 2*4%e=[2,5,4,5;2,3,9,6] ;f=[2,3,4,5;2,4,7,6];%creating two dimensional column matrix 4*2%g=[2,3;4,5;2,4;7,6] ;%performing arithmetic operation-addition%display('arithmetic operation-addition')

h=e+f%performing arithmetic operation-subtraction%i=e-f%performing arithmetic operation-multiplication%j=e*g%performing arithmetic operation-exponentiation%k=2.^am=0:1:2stem(m,k)%performing matrix operation-inverse%x=[2,3,4;4,6,5;5,6,7]

p=inv(x)%performing matrix operation-transpose%v=g'%performing matrix operation-rank%rank(e)

COMMAND WINDOW RESULT:-

h = 4 8 8 10 4 7 16 1i = 0 2 0 0 0 -1 2 0j = 67 77 76 93k = 4 8 16m = 0 1 2

x = 2 3 4 4 6 5 5 6 7

p = -1.3333 -0.3333 1.0000 0.3333 0.6667 -0.6667 0.6667 -0.3333 0v = 2 4 2 7 3 5 4 6ans = 2

FIGURES

CONCLUSIONThe given experiment has been performed successfully.

EXPERIMENT:2

AIM: Performing Matrix Manipulations - Concatenating, Indexing, Sorting, Shifting, Reshaping, Resizing and Flipping about a Vertical Axis / Horizontal Axis; Creating Arrays X & Y of given size (1 x N) and Performing (A). Relational Operations - >, = operator')X >= [9 2 3; 4 5 6; 7 8 10]display(' using operator')X > [9 2 3; 4 5 6; 7 8 10]display(' using < operator')X < [9 2 3; 4 5 6; 7 8 10]

% using logical operations%

m=[1 5;8 0]n=[2 0; 0 5]display(' using and operator')and(m,n)display(' using not operator')~mdisplay(' using or operator')or(m,n)display(' using xor operator')xor(m,n)

COMMAND WINDOW RESULT:-

a = 2 4 3 5 6 8 9 8 7

b = 2 5 8 5 9 4 4 7 5

horizontal concatenationc = 2 4 3 2 5 8 5 6 8 5 9 4 9 8 7 4 7 5vertical concatenationc = 2 4 3 5 6 8 9 8 7 2 5 8 5 9 4 4 7 5indexing two matricesd = 5 5 4 9 7 4 5 4 8sorting row wisef = 2 4 3 5 6 7 9 8 8sorting column wisef = 2 3 4 5 6 8 7 8 9h = 2 3 4 5 8 1 2 0 6 9 3 7reshaping the matrixg = 2 6 1 4 3 0 8 3 9 2 5 7rotating a matrix

i = 0 7 3 5 4 2 1 9 6 3 2 8flipping a matrixj = 7 0 5 3 2 4 9 1 3 6 8 2 resizing a matrixg = 2 6 1 4 3 0g = 2 1 4 3 0 shifting a matrixk = 0.1875 0.7690 0.6733 0.0594 0.2662 0.3960 0.4296 0.3158 0.7978 0.2729 0.4517 0.7727 0.4876 0.0372 0.6099 0.6964

l = 0.0372 0.6099 0.6964 0.4876 0.7690 0.6733 0.0594 0.1875 0.3960 0.4296 0.3158 0.2662 0.2729 0.4517 0.7727 0.7978

using >= operator

ans = 0 1 1 1 1 0 0 0 0 using operatorans = 0 1 1 1 0 0 0 0 0using < operatorans = 1 0 0 0 0 1 1 1 1m = 1 5 8 0n = 2 0 0 5 using and operatorans = 1 0 0 0 using not operatorans = 0 0 0 1 using or operatorans = 1 1 1 1 using xor operatorans = 0 1 1 1

CONCLUSION:-The given experiment has been performed successfully.

EXPERIMENT:3

AIM: Generating a set of Commands on a given Vector (Example: X = [1 8 3 9 0 1]) to (A). Add up the values of the elements (Check with sum) (B). Compute the Running Sum (Check with sum), where Running Sum for element j = the sum of the elements from 1 to j, inclusive. (C) Generating a Random Sequence using rand() / randn() functions and plot them.

TOOL USED: MATLAB 7.0

THEORY:

VECTORS:Matrices with one dimension equal to one and the other greater than one are called vectors. Here is an example of a numeric vector:A = [5.73 2-4i 9/7 25e3 .046 sqrt(32) 8j];size(A) % Check value of row and column dimensionsans = 1 7We can construct a vector out of other vectors, as long as the critical dimensions agree. All components of a row vector must be scalars or other row vectors. Similarly, all components of a column vector must be scalars or other column vectors: A = [29 43 77 9 21];B = [0 46 11];

C = [A 5 ones(1,3) B]C = 29 43 77 9 21 5 1 1 1 0 46 11

RANDOM:

rand:

Uniformly distributed random numbers and arrays SyntaxY = rand(n)Y = rand(m,n)Y = rand([m n])Y = rand(m,n,p,...)Y = rand([m n p...])Y = rand(size(A))s = rand('state')

The rand function generates arrays of random numbers whose elements are uniformly distributed in the interval (0,1).

Y = rand(n) returns an n-by-n matrix of random entries.An error message appears if n is not a scalar.

Y = rand(m,n) or Y = rand([m n]) returns an m-by-n matrix of random entries.

Y = rand(m,n,p,...) or Y = rand([m n p...]) generates random arrays.

Y = rand(size(A)) returns an array of random entries that is the same size as A. rand, by itself, returns a scalar whose value changes each time it's referenced.

s = rand('state') returns a 35-element vector containing the current state of the uniform generator.

randn:

Normally distributed random numbers and arrays SyntaxY = randn(n)Y = randn(m,n)Y = randn([m n])Y = randn(m,n,p,...)Y = randn([m n p...])Y = randn(size(A))randns = randn('state')

The randn function generates arrays of random numbers whose elements are normally distributed with mean 0, variance (sigma^2=1) , and standard deviation (sigma=1) .

Y = randn(n) returns an n-by-n matrix of random entries. An error message appears if n is not a scalar.

Y = randn(m,n) or Y = randn([m n]) returns an m-by-n matrix of random entries.

Y = randn(m,n,p,...) or Y = randn([m n p...]) generates random arrays.

Y = randn(size(A)) returns an array of random entries that is the same size as A. randn, by itself, returns a scalar whose value changes each time it's referenced.

s = randn('state') returns a 2-element vector containing the current state of the normal generator. To change the state of the generator

PROCEDURE:

1. ADD VALUES IN A VECTOR:

>> sum = 0;for i = 1:5 sum = sum+i;enddisplay(sum)

OUTPUTsum = 15

2. CHECK SUM:

>> A = [1 2 3 4 5]OUTPUTA = 1 2 3 4 5

>> B = sum(A)OUTPUTB = 15

3. CHECK RUNNING SUM:

>> sum = 0;>> for i = 1:5 sum = sum+i; display(sum) end

OUTPUTsum = 1sum = 3sum = 6sum = 10sum = 15

4. CHECK CUMSUM:

>> A = [1 2 3 4 5]OUTPUTA = 1 2 3 4 5>> B = cumsum(A)OUTPUTB = 1 3 6 10 15

5. RANDOM:

>> B = rand(3)OUTPUTB = 0.4447 0.9218 0.4057 0.6154 0.7382 0.9355 0.7919 0.1763 0.9169

>> plot(B)

>> B = randn(3)OUTPUTB = 0.1746 -0.5883 0.1139 -0.1867 2.1832 1.0668 0.7258 -0.1364 0.0593

>> plot(B)

EXPERIMENT:4

AIM: Evaluating a given expression and rounding it to the nearest integer value using Round, Floor, Ceil and Fix functions; Also, generating and Plots of (A) Trigonometric Functions - sin(t),cos(t), tan(t), sec(t), cosec(t) and cot(t) for a given duration, t. (B) Logarithmic and other Functions log(A), log10(A), Square root of A, Real nth root of A.

TOOL USED: MATLAB 7.0

THEORY:

Round Round to nearest integer Syntax: Y = round(X)Description: Y = round(X) rounds the elements of X to the nearest integers. For complex X, the imaginary and real parts are rounded independently.

FloorRound towards minus infinity Syntax B = floor(A)Description B = floor(A) rounds the elements of A to the nearest integers less than or equal to A. For complex A, the imaginary and real parts are rounded independently.

CeilRound toward infinitySyntax: B = ceil(A)Description: B = ceil(A) rounds the elements of A to the nearest integers greater than or equal to A. For complex A, the imaginary and real parts are rounded independently.

FixRound towards zero Syntax: B = fix(A)Description: B = fix(A) rounds the elements of A toward zero, resulting in an array of integers. For complex A, the imaginary and real parts are rounded independently.

Trigonometric FunctionsThe trigonometric functions are used along with their names and have the angle value as the parameters in them. A range for the value of the parameter is defined to attain their graphical representations. Syntax: A = trigonometric function name(Value)Ex. sin(30), cos(115), tan(-45)

PROCEDURE:

1. Evaluate given expression and round it to the nearest integer value using

1. ROUND

>>round(3.67)OUTPUTans = 4

2. FLOOR

>>floor(3.67)OUTPUTans = 3

3. CEIL

>>ceil(3.67)OUTPUTans = 4

4. FIX

>>a = [1.88 2.05 9.54 8.5]OUTPUTa = 1.8800 2.0500 9.5400 8.5000

>>fix(a)ans = 1 2 9 8

2. Generate plots of:

TRIGONOMETRIC FUNCTIONS

1. sin(t)

>> x=(0:0.01:2*pi);>> y=sin(x);>>plot(x,y);

OUTPUT

2. cos(t)

>> x=(0:0.01:2*pi);>> y=cos(x);>>plot(x,y);

OUTPUT

3. cosec(t)

>> x=(0:0.01:2*pi);>> y=csc(x);Warning: Divide by zero.> In csc at 14>>plot(x,y);

OUTPUT

4. sec(t)

>> x=(0:0.01:2*pi);>> y=sec (x);>>plot(x,y);

OUTPUT

5. tan(t)

>> x=(0:0.01:2*pi);>> y=sin(x);>>plot(x,y);

OUTPUT

6. cot(t)

>> x=(0:0.01:2*pi);>> y=cot(x);Warning: Divide by zero.> In cot at 14>>plot(x,y);

OUTPUT

3. LOGARITHMIC FUNCTIONS

6. log(t)

>> x=(0:0.01:20)>> plot(log(x))Warning: Log of zero

OUTPUT

2. log10(t)

>> x=(0.01:0.01:20)>> plot(log(x))

OUTPUT

EXPERIMENT:5

AIM: Creating a vector X with elements, Xn = (-1)n+1/(2n-1) and Adding up 100 elements of the vector, X; And, plotting the functions, x, x3, ex, exp(x2) over the interval 0 < x < 4 (by choosing appropriate mesh values for x to obtain smooth curves), on A Rectangular Plot

TOOL USED: MATLAB 7.0

THEORY:

Exponetial function is an elementary function that operates element-wise on arrays. Its domain includes complex numbers.Y = exp(X) returns the exponential for each element of X. For complex , it returns the complex exponential.

MATLAB PROGRAM:-

1. 2. Adding upto 100 elements>> n = 1:100; x = ( (-1).^(n+1) ) ./ (2*n - 1); y = sum(x)

x

plot(x(1,1:4))

x3a=x.^3;plot(a(1,1:4))

Exp(x)b=exp(x)plot(b(1,1:4))

Exp(n2)

c=exp(x.^2);plot(c(1,1:4))

COMMAND WINDOW RESULT:- y = 0.7829

FIGURES

CONCLUSION:-The given experiment has been performed successfully.

EXPERIMENT:6

AIM: Generating a Sinusoidal Signal of a given frequency (say, 100Hz) and Plotting with Graphical Enhancements - Titling, Labeling, Adding Text, Adding Legends, Adding New Plots to Existing Plot, Printing Text in Greek Letters, Plotting as Multiple and Subplot.

TOOL USED: MATLAB 7.0

THEORY:

The sin function operates element-wise on arrays. The function's domains and ranges include complex values. All angles are in radians.Y = sin(X) returns the circular sine of the elements of X.MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust the axes to spruce up the graph.1. Thexlabelandylabelcommands generate labels along x-axis and y-axis.2. Thetitlecommand allows you to put a title on the graph.3. Thegrid oncommand allows you to put the grid lines on the graph.4. Theaxis equalcommand allows generating the plot with the same scale factors and the spaces on both 5. axes.6. Theaxis squarecommand generates a square plot.Setting Colors on GraphMATLAB provides eight basic color options for drawing graphs. The following table shows the colors and their codes:ColorCode

Whitew

Blackk

Blueb

Redr

Cyanc

Greeng

Magentam

Yellowy

Setting Axis ScalesThe axis command allows you to set the axis scales. You can provide minimum and maximum values for x and y axes using the axis command in the following way:axis ( [xmin xmax ymin ymax] )

Generating Sub-PlotsWhen you create an array of plots in the same figure, each of these plots is called a subplot. Thesubplotcommand is for creating subplots.Syntax for the command is:subplot(m, n, p)where,mandnare the number of rows and columns of the plot array andpspecifies where to put a particular plot.

MATLAB PROGRAM:-

%Generating a Sinusoidal Signal of a given frequency with Titling, Labeling, Adding Text, Adding Legends, Printing Text in Greek Letters, Plotting as Multiple and Subplot. Time scale the generated signal for different values. E.g. 2X, 4X, 0.25X, 0.0625X. %

t=-0.25:0.0001:0.25;f1=3;y1=sin(2*pi*f1*t);y2=sin(2*pi*f1*2*t);y3=sin(2*pi*f1*4*t);y4=sin(2*pi*f1*0.25*t);y5=sin(2*pi*f1*0.625*t);plot(t,y1,'k',t,y2,'g',t,y3,'b',t,y4,'m',t,y5,'r')xlabel('Time(-0.2 < x < 0)')ylabel(' Amplitude (sine values)') title('Graph of sine waves having different time value')legend('y1','y2','y3','y4','y5')

FIGURES

CONCLUSION:-The given experiment has been performed successfully. EXPERIMENT:7

AIM: Solving First, Second and third Order Ordinary Differential Equation using Built-in Functions and plot.TOOL USED: MATLAB 7.0

THEORY:

Anordinary differential equationorODEis an equation containing a function of oneindependent variableand its derivatives. The term "ordinary" is used in contrast with the termpartial differential equationwhich may be with respect tomore thanone independent variable.

dsolve

Ordinary differential equation and system solver

S= dsolve(eqn)solves the ordinary differential equationeqn. Hereeqnis a symbolic equation containingdiffto indicate derivatives. Alternatively, you can use a string with the letterDindicating derivatives. For example,syms y(x); dsolve(diff(y) == y + 1)anddsolve('Dy = y + 1','x')both solve the equationdy/dx = y + 1with respect to the variablex. Also,eqncan be an array of such equations or strings.

S= dsolve(eqn,cond)solves the ordinary differential equationeqnwith the initial or boundary conditioncond.

SolvingUsedsolveto compute symbolic solutions to ordinary differential equations. You can specify the equations as symbolic expressions containingdiffor as strings with the letterDto indicate differentiation.

Before usingdsolve, create the symbolic function for which you want to solve an ordinary differential equation. Usesymorsymsto create a symbolic function. For example, create a functiony(x):syms y(x)

To specify initial or boundary conditions, use additional equations. If you do not specify initial or boundary conditions, the solutions will contain integration constants, such asC1,C2, and so on.The output fromdsolveparallels the output fromsolve. That is, you can: Calldsolvewith the number of output variables equal to the number of dependent variables. Place the output in a structure whose fields contain the solutions of the differential equations.

PROCEDURE:

>> y = dsolve('Dy = y*x','x');>> y = dsolve('Dy = y*x','y(1) = 1','x');>> x = linspace(0,1,20);>> z = eval(vectorize(y));>> plot(x,z);

Output:

>> eq1 = 'D2y + 8*Dy + 2*y = cos(x)';>> inits2 = 'y(0)=0, Dy(0)=1';>> y = dsolve(eq1,inits2,'x');>> x = linspace(0,1,20);>> z = eval(vectorize(y));>> plot(x,z);

Output:

>> eq1 = 'D3y + 3*D2y + Dy = cos(x)';>> inits2 = 'y(0)=0, Dy(0)=1,D2y(0)=3';>> y = dsolve(eq1,inits2,'x');>> x = linspace(0,1,20);>> z = eval(vectorize(y));>> plot(x,z);

Output:

EXPERIMENT:8

AIM: Writing brief Scripts starting each Script with a request for input (using input) to Evaluate the function h(T) using if-else statement, where, h(T) = (T 10) for 0 < T < 100 = (0.45 T + 900) for T > 100. Exercise: Testing the Scripts written using A). T = 5, h = -5 and B). T = 110, h =949.5

TOOL USED: MATLAB 7.0

THEORY:

Input Funtion:x= input (prompt)displays the text inpromptand waits for the user to input a value and press theReturnkey. The user can enter expressions, likepi/4orrand(3), and can use variables in the workspace. If the user presses theReturnkey without entering anything, theninputreturns an empty matrix. If the user enters an invalid expression at the prompt, then MATLABdisplays the relevant error message, and then redisplays the prompt.Example:str= input(prompt,'s')returns the entered text as a string, without evaluating the input as an expression.

If, Else, Else If Statements:ifexpression,statements, endevaluates anexpression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false.Theelseifandelseblocks are optional. The statements execute only if previous expressions in theif...endblock are false. Anifblock can include multipleelseifblocks.

Syntaxif expression statementselseif expression statementselse statementsendMATLAB PROGRAM:-

%Writing brief Scripts starting each Script with a request for input(using input) to Evaluate the function h(T) using if-else statement, where, h(T) = (T 10) for 0 < T < 100 = (0.45 T + 900) for T > 100. Exercise: Testing the Scripts written using A). T = 5, h = -5 and B). T = 110, h =949.5%

T=input('enter the value:')

if(T>0 & T100) h=(0.45*T+900) else disp('Enter a number greater than 0');

end

COMMAND WINDOW RESULT:-

>>enter the value:5

T =

5

h =

-5

>> enter the value:110

T =

110

h =

949.5000

>> enter the value:-98

CONCLUSION:-The given experiment has been performed successfully.

EXPERIMENT:9

AIM: Generating a Square Wave from sum of Sine Waves of certain Amplitude and Frequencies.

TOOL USED: MATLAB 7.0

THEORY:

hold on method:hold on retains plots in the current axes so that new plots added to the axes do not delete existing plots. New plots use the next colors and line styles basedontheColorOrderandLineStyleOrderproperties of the axes. MATLABadjusts axes limits, tick marks, and tick labels to display the full range of data.

MATLAB PROGRAM:-

%Generating a Square Wave from sum of Sine Waves of certain Amplitude and Frequencies.%

t=0:0.1:10;

y=sin(t);

z = sin(t) + sin(3*t)/3 + sin(5*t)/5 + sin(7*t)/7 + sin(9*t)/9;

plot(t,y,t,z);

legend('Sine wave','Square wave')

title('Generating square wave from sum of sine waves')

xlabel('Time period')

ylabel('Amplitude')

FIGURES

EXPERIMENT:10

AIM: Generating a Square Wave from sum of Sine Waves of certain Amplitude and Frequencies. Basic 2D and 3D plots: a) parametric space curve. b) polygons with vertices. c) 3D contour lines, pie and bar charts

TOOL USED: MATLAB 7.0

THEORY:

Contour Plots

A contour plot displays isolines of matrixZ. Label the contour lines usingclabel.

contour(X,Y,Z),contour(X,Y,Z,n), andcontour(X,Y,Z,v)draw contour plots ofZusingXandYto determine thexandyvalues. IfXandYare vectors, thenlength(X)must equalsize(Z,2)andlength(Y)must equalsize(Z,1). The vectors must be strictly increasing or strictly decreasing and cannot contain any repeated values. IfXandYare matrices, then their sizes must equal the size ofZ. Typically, you should setXandYso that the columns are strictly increasing or strictly decreasing and the rows are uniform (or the rows are strictly increasing or strictly decreasing and the columns are uniform).IfXorYis irregularly spaced, thencontourcalculates contours using a regularly spaced contour grid, and then transforms the data toXorY.

contour3creates a 3-D contour plot of a surface defined on a rectangular grid.

contour3(X,Y,Z),contour3(X,Y,Z,n), andcontour3(X,Y,Z,v)draw contour plots ofZusingXandYto determine thexandyvalues. IfXandYare vectors, thenlength(X)must equalsize(Z,2)andlength(Y)must equalsize(Z,1). The vectors must be strictly increasing or strictly decreasing and cannot contain any repeated values. IfXandYare matrices, then their sizes must equal the size ofZ. Typically, you should setXandYso that the columns are strictly increasing or strictly decreasing and the rows are uniform (or the rows are strictly increasing or strictly decreasing and the columns are uniform).IfXorYis irregularly spaced, then contour3calculates contours using a regularly spaced contour grid, and then transforms the data toXorY.

Bar Graph Plot

bar(y)creates a bar graph with one bar for each element iny. Ifyis a matrix, thenbargroups the bars according to the rows iny.

bar3draws a three-dimensional bar graph.

bar3(Y)draws a three-dimensional bar chart, where each element inYcorresponds to one bar. WhenYis a vector, thex-axis scale ranges from1tolength(Y). WhenYis a matrix, thex-axis scale ranges from1tosize(Y,1)and the elements in each row are grouped together.

Pie Chart Plot

pie(X)draws a pie chart using the data inX. Each slice of the pie chart represents an element inX. Ifsum(X) 1, then the values inXdirectly specify the areas of the pie slices.piedraws only a partial pie ifsum(X) < 1. Ifsum(X) > 1, thenpienormalizes the values byX/sum(X)to determine the area of each slice of the pie. IfXis of data typecategorical, the slices correspond to categories. The area of each slice is the number of elements in the category divided by the number of elements inX.

pie3(X)draws a three-dimensional pie chart using the data inX. Each element inXis represented as a slice in the pie chart. Ifsum(X) 1, then the values inXdirectly specify the area of the pie slices.pie3draws only a partial pie ifsum(X) < 1. If the sum of the elements inXis greater than one, thenpie3normalizes the values byX/sum(X)to determine the area of each slice of the pie.

Sphere Plot

Thespherefunction generates thex-,y-, andz-coordinates of a unit sphere for use withsurfandmesh.spheregenerates a sphere consisting of 20-by-20 faces.sphere(n)draws asurfplot of ann-by-nsphere in the current figure.[X,Y,Z] = sphere(n)returns the coordinates of a sphere in three matrices that are(n+1)-by-(n+1)in size. You draw the sphere withsurf(X,Y,Z)ormesh(X,Y,Z).

Line Plots

Theplot3function displays a three-dimensional plot of a set of data points.

plot3(X1,Y1,Z1,...), whereX1,Y1,Z1are vectors or matrices, plots one or more lines in three-dimensional space through the points whose coordinates are the elements ofX1,Y1, andZ1.

Polygon Plots

Thefillfunction creates colored polygons.

fill(X,Y,C)creates filled polygons from the data inXandYwith vertex color specified byC.Cis a vector or matrix used as an index into the colormap. IfCis a row vector,length(C)must equalsize(X,2)andsize(Y,2); ifCis a column vector,length(C)must equalsize(X,1)andsize(Y,1). If necessary,fillcloses the polygon by connecting the last vertex to the first.

Thefill3function creates flat-shaded and Gouraud-shaded polygons.

fill3(X,Y,Z,C)fills three-dimensional polygons.X,Y, andZtriplets specify the polygon vertices. IfX,Y, orZis a matrix,fill3createsnpolygons, wherenis the number of columns in the matrix.fill3closes the polygons by connecting the last vertex to the first when necessary.

Cylinder Plot

cylindergeneratesx-,y-, andz-coordinates of a unit cylinder. You can draw the cylindrical object usingsurformesh, or draw it immediately by not providing output arguments.[X,Y,Z] = cylinderreturns thex-,y-, andz-coordinates of a cylinder with a radius equal to1. The cylinder has 20 equally spaced points around its circumference.

PROCEDURE:

Parametric Space Curves>> t = 0:pi/50:10*pi;>> st = sin(t);>> ct = cos(t);>> plot3(st,ct,t);

Output:

Polygons With Vertices

>> t = (1/16:1/8:1)'*2*pi;>>x = cos(t);>>y = sin(t);>>fill(x,y,'g')>>axis square

Output:

>>patch([0 0 1 1],[0 1 1 0],[1 1 1 1],'r') >>patch([0 1 1 0],[0 0 0 0],[0 0 1 1],'r') >>patch([0 0 0 0],[0 1 1 0],[0 0 1 1],'r')>>view(-37.5, 30)>>axis square

Output:

>> X = [0 1 1 2; 1 1 2 2; 0 0 1 1];>>Y = [1 1 1 1; 1 0 1 0; 0 0 0 0];>>Z = [1 1 1 1; 1 0 1 0; 0 0 0 0];>>C = [0.5000 1.0000 1.0000 0.5000; 1.0000 0.5000 0.5000 0.1667; 0.3330 0.3330 0.5000 0.5000];>>figure>>fill3(X,Y,Z,C)

Output:

3-D Contour Lines, Pi Charts and Bar Graphs

>>x = -2:0.25:2;>>[X,Y] = meshgrid(x);>>Z = X.*exp(-X.^2-Y.^2);>>contour3(X,Y,Z,30)

Output:

>>x = -2:0.2:2;>>y = -2:0.2:3;>>[X,Y] = meshgrid(x,y);>>Z = X.*exp(-X.^2-Y.^2);>>figure contour(X,Y,Z,'ShowText','on')

Output:

>> z = magic(5);>> b = bar3(z);

>> x = [1,2,3,4,5,6,7,8];>> pie3(x);

Output:

>> x = [1,2,3,4,5,6,7,8];>> pie(x);

Output:

>> z = magic(5);>> b = bar3(z);

Output:

>> figure>> cylinder

>> z = magic(5);>> b = bar3(z);

Output: