Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml


Introducere in matrici

Matlab



+ Font mai mare | - Font mai mic



Introducere in matrici

MATLAB lucreaza in principal numai cu un fel de obiect, de exemplu o matrice numerica dreptunghiulara cu intrari posibil complexe; matricile reprezinta toate variabilele. In anumite situatii matricile 1-by-1 (1 x 1) sunt interpretate ca scalari iar matricile cu un singur rand (1 x n) sau cu o coloana (m x 1) sunt interpretate ca vectori. Matricile pot fi introduse in MATLAB in mai multe cai diferite:



  • Intrate printr-o lista explicita de elemente
  • Create in M-files
  • Incarcare din fisier extern de date (a se vedea Guidul de utilizare)
  • Generat prin declaratii si functii

De exemplu, fie declaratiile

 A = [1 2 3; 4 5 6; 7 8 9]

si

 A = [
 1 2 3
 4 5 6
 7 8 9 ]

creates the obvious 3-by-3 matrix and assign it to a variable A. Try it! The elements with a row of a matrix may be seperated by commas as well as a blank. So the above statements are the same as:

 A = [1,2,3; 4,5,6; 7,8,9]

and

 A = [
 1,2,3
 4,5,6
 7,8,9 ]

When listing a number in exponential form (eg. 1.23e-4), blank spaces must be avoided. Listing entries of a large matrix is best done in an M-file or an ASCII file, where errors can be easily edited away. ASCII files should contain a rectangular array of just the numeric matrix entries. If this file is named, say, data.ext (where .ext is any extension), the MATLAB command load data.ext will read this file to the variable data in your MATLAB workspace. The built-in functions rand, magic and hilb, for example, provide an easy way to create matrices with which to experiment. The command rand(n) will create an n n matrix with randomly generated entries distributed uniformly between 0 and 1, while rand(m,n) will create an m n one. magic(n) will create an integral n n matrix which is a magic square (rows and columns have common sum); hilb(n) will create the n n Hilbert matrix, the king of ill-conditioned matrices (m and n denote positive integers). Matrices can also be generated with a for-loop. Individual matrix and vector entries can be referenced with indices inside parentheses in the usual manner. For example, A(1,2) denotes the entry in the first row, second column of matrix A and x(3) denotes the third coordinate of vector x. Try it! A matrix or a vector will only accept positive integers as indices.

Operatii cu matrici si tablouri

The following matrix operations are available in MATLAB:

+

-

*

^

'

/

addition

subtraction

multiplication

power

transpose

left division

right division

These matrix operations apply to scalars (1-by-1 matrices) as well. If the sizes of the matrices are incompatible for the matrix operation, an error message will be generated, except in the case of scalar-matrix operations (for addition, subtraction, multiplication and division) in which case each entry of the matrix is operated on by the scalar. The 'matrix division' operations deserve special comment. If A is an invertible square matrix and b is a compatible column, respectively row vector, then

  • x = Ab is the solution of A*x = b
  • x = b/A is the solution of x*A = b

In left division, if A is square, then it is factored using Gaussian elimination and these factors are used to solve A*x = b. If A is not square, it is factored using Householder orthogonalization with column pivoting and the factors are used to solve the under- or over- determined system in the least squares sense. Right division is defined in terms of left division by b/A = (A'b'). The matrix operations of addition and subtraction already operate entry-wise but the other matrix operations given above do not, they are matrix operations. It is important to observe that these other operations: *, ^, , /, can be made to operate entry-wise by preceding them by a period. For example, either

 [1,2,3,4] .* [1,2,3,4]

or

 [1,2,3,4] .^ 2

will yield [1,4,9,16]. Try it! This is particularly useful when using MATLAB graphics.

Declararea expresiilor si variabilelor; salvarea ubei sectiuni

MATLAB is an expression language; the expressions you type are interpreted and evaluated. MATLAB's statements are usually of the form:

variable = expression, or simply
expression

Expressions are usually composed from operators, functions and variable names. Evaluation of the expression produces a matrix, which is then displayed on the screen and assigned to the variable for future use. If the variable name and = sign are omitted, a variable ans (for answer) is automatically created to which the result is assigned.

A statement is normally terminated with the carriage return. However, a statement can be continued on the next line with three or more periods followed by a carriage return. On the other hand, several statements can be placed on a single line if seperated by commas or semicolons.

If the last character of a statement is a semicolon, then printing to the screen will be suppressed, but the assignment is still carried out. This is essential in suppressing unwanted printing of intermediate results.

MATLAB is case-sensitive in the names of commands, function and variables. For example, solveUT is not the same as solveut.

The command whos will list the variables currently in the workspace and their size. A variable can be cleared from the workspace with the command clear variablename. The command clear alone will clear all nonpermanent variables.

The permanent variable eps (epsilon) gives the machine precision---about 2.2204e-16 on our machine. It is useful in determining tolerences for convergence of iterative processes.

A runaway display or computation can be stopped on most machines without leaving MATLAB with [Ctrl-C].

When one logs out or exits MATLAB, all variables are lost. However, invoking the command save before exiting causes all variables to be written to a binary file named matlab.mat. When one later reenters MATLAB, the command load will restore the workspace to its former state.

Constructia functiilor matriciale

Convenient matrix building functions are

eye

zeros

ones

diag

triu

tril

rand

hilb

magic

identity matrix

matrix of zeros

matrix of ones

see below

upper triangular part of a matrix

lower triangular part of a matrix

randomly generated matrix

Hilbert matrix

magic square

For example, zeros(m,n) produces an m n matrix of zeros and zeros(n) produces an n n one; if A is a matrix, then zeros(A) produces a matrix of zeros of the same size as A. If x is a vector, diag(x) is the diagonal matrix with x down the diagonal; if A is a square matrix:

 A =
 1 2 3
 4 5 6
 7 8 9

then diag(A) is a vector consisting of the diagonal of A. What is diag(diag(A))? Try it. Matrices can be built from blocks. For example, if A is a 3-by-3 matrix, then

 B = [A, zeros(3,2); ones(2,3), eye(2)]

will build a certain 5-by-5 matrix. Try it!

For, while, if, and relations

Like most computer languages, MATLAB offers a variety of flow control statements like for, while and if. The statements that we use to control the flow are called relations.

Declarare For

For example, for a given n, the statement

 x = []; for i =1:n, x=[x,i^2], end

or

 x = [];
 for i = 1:n
  x = [x,i^2]
 end

will produced a certain n-vector and the statement

 x = []; for i = n:-1:1, x=[x,i^2], end

will produced the same vector in reverse order. Try them. Note that a matrix may be empty (such as x = []). The statements

 for i = 1:m
  for j = 1:n
  H(i,j) = 1/(i+j-1);
  end
 end
 H

will produced and print to the screen the m n hilbert matrix. The semicolon on the inner statement suppresses printing of unwanted intermediate results while the last H displays the final result.

Declarare While

The general form of a while loop is

while relation

statements

end

The statements will be repeatedly executed as long as the relation remains true. For example, for a given number a, the following will compute and display the smallest nonnegative integer n such that 2 to the power of n is > a:

 n = 0;
 while 2^n <= a
  n = n + 1;
 end
 n

Declarare If

The general form of a simple if statement is

if relation

statements

end

The statements will be executed only if the relation is true. Multiple branching is also possible, as illustrated by

 if n < 0
  parity = 0;
 elseif rem(n,2) == 0
  parity = 2;
 else
  parity = 1
 end

In two-way branching the elseif portion would be omitted.

Relatii

The relational operators in MATLAB are

 < less than
 > greater than
 <= less than or equal
 >= greater than or equal
 == equal
 ~= not equal

Note that '=' is used in an assigment statement while '==' is used in a relation. Relations may be connected or quantified by the logical operators:

 & and
 | or
 ~ not

When applied to scalars, a relation is actually the scalar 1 or 0 depending on whether the relation is true or false. Try 3 < 5, 3 > 5, 3 == 5 and 3 == 3. When applied to matrices of the same size, a relation is a matrix of 0's and 1's giving the value of the relation between corresponding entries. Try a = rand(5), b = triu(a), a == b. A relation between matrices is interpreted by while and if to be true if each entry of the relation matrix is nonzero. Hence, if you wish to execute statement when matrices A and B are equal, you could type

if A == B

statement

end

but if you wish to execute statement when A and B are not equal, you would type

if any(any(A ~= B))

statement

end

or more simply,

if A == B else

statement

end

Note that the seemingly obvious

if A ~= B, statement, end

will not give what is intended since statement would be executed only if each of the corresponding entries of A and B differ. The functions any and all can be creatively used to reduced matrix relations to vectors or scalars. Two any's are required above since any is a vector operator. The for statement permits any matrix to be used instead of 1:n. See the User's Guide for details of how this feature expands the power of the for statement.

Functii scalare

Certain MATLAB functions operate essentially on scalars, but operate element-wise when applied to a matrix. The most common such functions are:

 sin cos tan
 asin acos atan
 sinh cosh tanh
 exp log(natural log) rem(remainder)
 abs sqrt sign

round floor ceil

Functii vectoriale

Other MATLAB functions operate essentially on a vector (row or column), but act on an m n matrix in a column-by-column fashion to produce a row vector containing the results of their application to each column. Row-by-row action can be obtained by using transpose. For example, mean(A')'. A few of these functions are:

 max sum median any
 min prod mean all
 sort std

For example, the maximum entry in a matrix A is given by max(max(A)) rather than max(A). Try it!

Functii matriciale

Much of MATLAB's power comes from its matrix functions. The most useful ones are:

eig

eigenvalues and eigenvectors

chol

cholesky factorization

svd

singular value decomposition

inv

inverse

lu

LU factorization

qr

QR factorization

hess

hessenberg form

schur

schur decomposition

rref

reduced row echelon form

expm

matrix exponential

sqrtm

matrix square root

poly

characteristic polynomial

det

determinant

size

size

norm

1-norm, 2-norm, F-norm, infinity-norm

cond

condition number in the 2-norm

rank

rank

MATLAB functions may have single or multiple output arguments. For example,

y = eig(A), or simply eig(A)

produces a column vector containing the eigenvalues of A while

[U,D] = eig(A)

produces a matrix U whose columns are the eigenvectors of A and a diagonal matrix D with the eigenvalues of A on its diagonal. Try it!

Editare si apelare linie de comanda

The command line in MATLAB can be easily edited. The cursor can be positioned with the left/right arrows and the Backspace key used to delete the character to the left of the cursor. Other editing features are also available. See help cedit. A convenient feature is use of the up/down arrows to scroll through the stack of previous commands. One can, therefore, recall a previous command line, edit it and execute the revised command line. For small routines, this is much more convenient than using an M-file which requires moving between MATLAB and the editor. For example, flopcounts for computing the inverse of matrices of various sizes could be compared by repeatedly recalling, editing and executing

 a = rand(8); flops(0); inv(a); flops

If one wanted to compare plots of the functions y = sinmx and y = sinnx on the interval [0,2*pi] for various m and n, one might do the same for the command line:

m=2; n=3; x=0:.01:2*pi; y=sin(m*x); z=cos(n*x); plot(x,y,x,z)

Notarea submatricilor si coloanelor

Vectors and submatrices are often used in MATLAB to achieve fairly complex data manipulation effects. 'Colon notation' (which is used both to generate vectors and reference submatrices) and subscripting by vectors are keys to efficient manipulation of these objects. Creative use of these features permits one to minimize the use of loops (which slows down MATLAB) and to make code simple and readable. Special effort should be made to become familiar with them. The expression 1:5 (met earlier in for statements) is actually the row vector [1 2 3 4 5]. The numbers need not be integers nor the increment one. For example,

 0.2:0.2:1.2 = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2]

and

 5:-1:1 = [5 4 3 2 1]

The following statements will, for example, generate a table of sines.

 x = [0.0:0.1:2.0]';
 y = sin(x);
 [x y]

Try it! Note that since sin operates entry-wise, it produces a vector y from the vector x. The colon notation can be used to access submatrices of a matrix. For example, A(1:4,3) is the column vector consisting of the first four entries of the third column of A. A colon by itself denotes an entire row or column:

 A(:,3) is the third column of A, and
 A(1:4,:) is the first 4 rows of A

Arbitrary integral vectors can be used as subscripts:

 A(:,[2 4]) contains as columns, column 2 and 4 of A

Such subscripting can be used on both sides of an assignment statement:

 A(:,[2 4 5]) = B(:,1:3) replaces columns 2, 4, 5 of A
 with the first three columns of B. Note that the entire
 altered matrix A is printed and assigned.

Columns 2 and 4 of A can be multiplied on he right by the 2-by-2 matrix [1 2; 3 4]:

 A(:,[2,4]) = A(:,[2,4])*[1 2; 3 4]

Once again, the entire altered matrix is printed and assigned. If x is an n-vector, what is the effect of the statement

 x = x(x:-1:1) ?

Give it a try and see the result for yourself. to appreciate the usefulness of these features, compare these MATLAB statements with a Pascal, FORTRAN or C routines that have the same effect.

Fisiere M

MATLAB can execute a sequence of statements stored in a file. Such files are called 'M-files' because they must have an extension of '.m' for its filename. Much of your work with MATLAB will be creting and refining M-files. There are two types of M-files: script files and function files.

Fisiere Script

A script file consists of a sequence of normal MATLAB statements. If the file has the filename, say, rotate.m, then the MATLAB command rotate will cause the statements in the file to be executed. Variables in a script file are global and will change the value of variables of the same name in the environment of the current MATLAB session. Script files are often used to enter data into a large matrix; in such a file, entry errors can be easily edited out. If, for example, one enters in a diskfile data.m

 A = [
 1 2 3 4
 5 6 7 8
 ];

then the MATLAB statement data will cause the assignment given in data.m to be carried out.

An M-file can also reference other M-files, including referencing itself recursively.

Fisiere Function

Function files provide extensibility to MATLAB. You can create new functions specific to your problem which will then have the same status as other MATLAB functions. Variables in a function file are by default local. However, you can declare a variable to be global if you wish. We first illustrate with a simple example of a function file.

 function y = randint(m,n)
 % RANDINT Randomly generated integral matrix.
 % randint(m,n) returns an m-by-n such matrix with
 % entries between 0 and 9.
 y = floor(10*rand(m,n));

A more general version of this function is given as follow:

 function y = randint(m,n,a,b)
 % RANDINT Randomly generated integral matrix.
 % randint(m,n) returns an m-by-n such matrix with
 % entries between 0 and 9.
 % randint(m,n,a,b) returns entries between integers a and b.
 if nargin < 3, a=0; b=9; end
 y = floor((b-a+1)*rand(m,n))+a;

This should be placed in a diskfile with filename randint.m (corresponding to the function name). The first line declares the function name, input arguments and output arguments; without this line the file would be a script file. Then a MATLAB statement z = randint(4,5), for example, will cause the numbers 4 and 5 to be passed to the variables m and n in the function file with the output result being passed out to the variable z. Since variables in a function file are local, their names are independent of those in the current MATLAB environment. Note that use of nargin ('number of input arguments') permits one to set a default value of an omitted input variable---such as a and b in the example given above. A function may also have multiple output arguments. For example:

 function [mean, stdev] = stat(x)
 % STAT Mean and standard deviation
 % For a vector x, stat(x) returns the
 % mean and standard deviation of x.
 % For a matrix x, stat(x) returns two row
 % vectors containing, respectively, the
 % mean and standard deviation of each column.
 [m n] = size(x);
 if m == 1
 m = n; % handle case of a row vector
 end
 mean = sum(x)/m;
 stdev = sqrt(sum(x.^2)/m -mean.^2);

Once this is placed in a diskfile stat.m, a MATLAB command [xm, xd] = stat(x), for example. will assign the mean and standard deviation of the entries in the vector x to xm and xd, respectively. Single assignments can also be made with a function having multiple output arguments. For example, xm = stat(x) (no brackets needed around xm) will assign the mean of x to xm. The % symbol indicates that the rest of the line is a comment; MATLAB will ignore the rest of the line. However, the first few comments lines, which document the M-file, are available to the on-line help facility and will be displayed if, for example, help stat is entered. Such documentation should always be included in a function file. This function illustrates some of the MATLAB features that can be used to produce efficient code. Note, for example, that x.^2 is the matrix squares of the entries of x, that sum is a vector function, that sqrt is a scalar function, and that the division in sum(x)/m is a matrix-scalar operation. The following function, which gives the greatest common divisor of two integers via the Euclidean algorithm, illustrates the use of an error message.

 function y = gcd(a,b)
 % GCD Greatest common divisor
 % gcd(a,b) is the greatest common divisor
 % of the integers a and b, not both zero.
 a = round(abs(a)); b = round(abs(b));
 if a == 0 & b == 0
 error('The gcd is not defined when both numbers are zero')
 else
 while b ~= 0
 r = rem(a,b);
 a = b; b = r;
 end
 end

Some more advanced features are illustrated by the following function. As noted earlier, some of the input arguments of a function---such as tol in the following example, may b made optional through use of nargin ('number of input arguments'). The variable nargout can be similarly used. Note that the fact that a relation is a number (1 when true; 0 when false) is used and that, when while of if evalutes a relation, 'nonzero' means 'true' and 'zero' means 'false'. Finally, the MATLAB function feval permits one to have as an input variable a string naming function.

 function [b, steps] = bisect(fun, x, tol)
 % BISECT Zero of a function of one variable via bisection method.
 % bisect(fun,c) returns a zero of the function. fun is a string
 % containing the name of a real-valued function of a single real
 % variable; ordinarily functions are defined in M-files. x is a
 % starting guess. The value returned is near a point where fun
 % changes sign. For example, bisect('sin',3) is pi. Note the
 % quote around sin.
 %
 % An optional third input argument seets a tolerance for the
 % relative accuracy of the result. The default is eps. An
 % optional second output arguments gives a matrix containing
 % a trace of the steps; the rows are of the form [c f(c)].
 % Initialization
 if nargin < 3, tol = eps; end
 trace = (nargout == 2);
 if x ~= 0, dx = x/20; else, dx = 1/20; end
 a = x - dx; fa = feval(fun,a);
 b = x + dx; fb = feval(fun,b);
 % Find change of sign
 while (fa > 0) == (fb > 0)
 dx = 2.0*dx;
 a = x - dx; fa = feval(fun,a);
 if (fa > 0) ~= (fb > 0), break, end 
b = x + dx; fb = feval(fun,b);
 end
 if trace, steps = [a fa; b fb]; end
 % Main loop
 while abs(b - a) > 2.0*tol*max(abs(b),1.0)
 c = a + 0.5*(b - a); fc = feval(fun,c);
 if trace, steps = [steps; [c fc]]; end
 if (fb > 0) == (fc > 0)
 b = c; fb = fc;
 else
 a = c; fa = fc;
 end
 end

Some of MATLAB's functions are built-in while others are distributed as M-files. The actual listing of any M-file---MATLAB's or your own---can be viewed with the MATLAB command type functionname. Try entering type eig, type vander and type rank.

Text strings, error messages, input

Text strings are entered into MATLAB surrounded by single quotes. For example,

 s = 'This is a test'

assign the given text string to the variable s.

Text strings can be displayed with the function disp. For example:

 disp('this message is hereby displayed') or
 fprintf('this message is hereby displayedn')

Error messages are best displayed with the function error

 error('Sorry, the matrix must be symmetric')

since when placed in an M-file, it causes execution to exit the M-file.

In an M-file, the user can be prompted to interactively enter input data with the function input. When, for example, the statement

 iter = input('Enter the number of iterations: ')

is encountered, the prompt message is displayed and execution pauses while the user keys in the input data. Upon pressing the return key, the data is assigned to the variable iter and execution resumes.

Managing M-files

While using MATLAB, one frequently wishes to create or edit an M-file and then return to MATLAB. One wishes to keep MATLAB active while editing a file since otherwise all variables would be lost upon exiting. This can be easily done using the !-feature. If while in MATLAB, you precede it with an !, any system command---such as those for editing, printing or copying a file---can be executed without exiting MATLAB. For example, the MATLAB command

 >> !emacs rotate.m &

will let you edit the file named rotate.m using the emacs editor. As noted in lesson 1, it is advisable to open two windows, keeping MATLAB active in one window and your editor active in the other.

Comparing efficiency of algorithms: flops and etime

Two measures of the efficiency of an algorithm are the number of floating point operations (flops) performed and the elapsed time. The MATLAB function flops keeps a running total of the flops performed. The command flops(0) (not flops = 0!) will reset flops to 0. Hence entering flops(0) immediately before executing an algorithm and flops immediately after gives the flop count for the algorithm. The MATLAB function clock gives the current time accurate to a hundreth of a second (see help clock). Given two such times t1 and t2, etime(t2,t1) gives the elapsed time from t1 to t2. One can for example, measure the time required to solve a given linear system Ax = b using Gaussian elimintation as follows:

 t = clock; x = Ab; time = etime(clock,t)

You may wish to compare this time---and flop count---with that for solving the system using x = inv(A)*b;. Try it! Others related commands are tic and toc. It should be noted that, on timesharing machine, etime may not be a reliable measure of the eficiency of an algorithm since the rate of execution depends on how busy the computer is at that particular time when you execute your program.

Output format

While all computations in MATLAB are performed in double precision, the format of the displayed output can be controlled by the following commands.

 format short fixed point with 4 decimal places(the default)
 format long fixed point with 14 decimal places
 format short e scientific notation with 4 decimal places
 format long e scientific notation with 15 decimal places

Once invoked, the chosen format remains in effect until changed. The command format compact will suppress most blank lines allowing more information to be placed on the screen or page. It is independent of the other format commands.

Hardcopy

Hardcopy is most easily obtained with the diary command. The command

diary filename

causes what appears subsequently on the screen (except graphics) to be written to the named diskfile (if the filename is omitted, it will be written to a default file named diary) until one gives the command diary off; the command diary on will cause writing to the file to resume, overwriting the contents of the file that you previously created. When finished, you can edit the file as desired and print it out on the local system. The !-feature will permit you to edit and print the file without leaving MATLAB.

Graphics

MATLAB can produce both planar plots, images, and 3-D mesh surface plots. To preview some of these capabilities and others as well, enter the command demos.

Planar plots

The plot command creates linear x-y plots; if x and y are vectors of the same length, the command plot(x,y) opens a graphics window and draws an x-y plot of the elements of x versus the elements of y. You can, for example, draw the grapho of the sine function over the interval -4 to 4 with the following commands:

 x = -4:.01:4; y = sin(x); plot(x,y)

Give it a try. The vector x is a partition of the domain with meshsize 0.01 while y is a vector giving the values of sine at the nodes of this partition (recall that sin operates entrywise). As a second example, we will draw the graph of a exponential function:

 x = -1.5:.01:1.5; y = exp(-x.^2); plot(x,y)

Note that one must precede ^ by a period to ensure that it operates entrywise.

Plots of parametrically defined curves can also be made. Try, for example,

 t=0:.001:2*pi; x=cos(3*t); y=sin(2*t); plot(x,y)

The command grid will place grid lines on the current graph. The graphs can be given titles, axes labeled and text placed within the graph with the following commands which take a string as an argument.

 title graph title
 xlabel x-axis label
 ylabel y-axis label
 gtext interactively-positioned text
 text position text at specific coordinates

For example, the command

 title('Best Least Squares Fit')

gives the graph a title. The command gtext('The Spot') allows a mouse or the arrow keys to position a crosshair on the graph, at which the text will be placed when any key is pressed.

By default, the axes are auto-scaled. This can be overridden by the command axis. If c = [xmin,xmax,ymin,ymax] is a 4-element vector, then axis(c) sets the axis scaling to the prescribed limits. By itself, axis freezes the current scaling for subsequent graphs; entering axis again returns to auto-scaling. The command axis('square') ensures that the same scale is used on both axes. For more informations on axis see help axis. Two ways to make multiple plots on a single graph are illustrated by

 x=0:.01:2*pi;y1=sin(x);y2=sin(2*x);y3=sin(4*x);plot(x,y1,y2,y3)

and by forming a matrix Y containing the functional values as columns

 x=0:.01:2*pi; Y=[sin(x)', sin(2*x)', sin(4*x)']; plot(x,Y)

Another way is with the hold command. The command hold freezes the current graphics screen so that subsequent plots are superimposed on it. Entering hold again releases the 'hold'. The commands hold on and hold off are also available. One can override the default linetypes and pointtypes. For example,

 x=0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x);
 plot(x,y1,'--',x,y2,':',x,y3,'+')

renders a dashed line and dotted line for the first two graphs while for the third the symbol + is placed at each node. The line- and mark-type are

 Linetypes: dashed(--), dotted(:), dashdot(-.), and the default solid(-)
 Marktypes: point(.), plus(+), star(*), circle(o), x-mark(x), square(s), 
diamond(d), up-triangle(v), down-triangle(^), 
left-triangle(<), right-triangle(>), pentagram(p), 
hexagram(h)
 Colors: yellow(y), magenta(m), cyan(c), red(r), green(g), white(w), 
black(k), and the default blue(b)

See help plot for line and mark colors.

The command subplot can be used to partition the screen so that up to four plots can be viewed simultaneously. See help subplot.

Images

Matrices could be viewed as an image, since any digital image is like a matrix in that it has rows and columns of values. The command image(A) will 'image' the matrix A. The matrix will be displayed differently depending on the colormap . The colormap can consist of 16 colors or 256 colors; changing how many colors are used will alter the way the matrix is displayed. In order to avoid this alteration due to differences in the number of colors you can use the command imagesc(A) which will automatically scale your matrix to span the entire spectrum of colors possible.

3-D mesh plots

Three dimensional mesh surface plots are drawn with the function mesh. The command mesh(z) creates a three-dimensional perspective plot of the elements of the matrix z. The mesh surface is defined by the z-coordinates of the points above a rectangular grid in the x-y plane. Try mesh(eye(10)).

To draw the graph of a function z = f(x,y) over a rectangle, one first defines vectors xx and yy which gives partitions of the sides of the rectangle. With the function meshgrid (mesh grid) on then creates a matrix x, each row of which equals xx and whose column length is the length of yy, and similarly a matrix y, each column of which equals yy, as follows:

 [x,y] = meshgrid(xx,yy);

One then computes a matrix z, obtained by evaluating f entrywise over the matrices x and y, to which mesh can be applied.

The following example will draws the graph of z = exp(-sqr(x)-sqr(y)) over the square [-2,2] times [-2,2].

 xx = -2:.1:2;
 yy = xx;
 [x,y] = meshgrid(xx,yy);
 z = exp(-x.^2 - y.^2);
 mesh(z)

Alternatively, you could replace the first three lines of the preceeding example with:

 [x,y] = meshgrid(-2:.1:2,-2:.1:2);

For more details regarding the command mesh, you can refer to online help or the User's Guide.

Others command related to 3-D graphics are plot3 and surf; where plot3 is used to draw a line in the 3-D space while surf is used to draw a surface in the 3-D space. See the online help for furthur details of these commands. You can obtain a hardcopy of the graphics screen by using the command print. The print -Pps1 command will send a high-resolution copy of the current graphics screen to the printer ps1, placing the graph on the centre of the page. Also, if you want to print two graphics screen into a file called test.ps, what you can do is:

 plot first graph
 print test
 plot second graph
 print -append test

What the above example do is it will first print the first graph that you have drawn in the file test.ps and the second print statement will append the second graph to the same file. After this, you can print the file using the standard unix command lpr. Finally, use the close command to close the graphics screen.

B =
 1 2 3 0 0
 4 5 6 0 0
 7 8 9 0 0
 1 1 1 1 0
 1 1 1 0 1

Colormaps

 hsv - Hue-saturation-value color map.
 hot - Black-red-yellow-white color map.
 gray - Linear gray-scale color map.
 bone - Gray-scale with tinge of blue color map.
 copper - Linear copper-tone color map.
 pink - Pastel shades of pink color map.
 white - All white color map.
 flag - Alternating red, white, blue, and black color map.
 lines - Color map with the line colors.
 colorcube - Enhanced color-cube color map.
 jet - Variant of HSV.
 prism - Prism color map.
 cool - Shades of cyan and magenta color map.
 autumn - Shades of red and yellow color map.
 spring - Shades of magenta and yellow color map.
 winter - Shades of blue and green color map.
 summer - Shades of green and yellow color map.

(do a help colormap for more information)



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 2987
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved