You are on page 1of 20

GEOSTATISTICAL ANALYSIS

Lecturer: Dr. Taher Buyung

MATLAB TOTURIAL PRIMARY SECTION


Tutor: Mohammad Khazraei Manesh

Overview of the MATLAB Environment


MATLAB is a high-level technical computing language and interactive environment for algorithm development, data visualization, data analysis, and numeric computation. Using the MATLAB product, you can solve technical computing problems faster than with traditional programming languages, such as C, C++, and Fortran. You can use MATLAB in a wide range of applications, including signal and image processing, communications, control design, test and measurement, financial modeling and analysis, and computational biology. Add-on toolboxes (collections of special-purpose MATLAB functions, available separately) extend the MATLAB environment to solve particular classes of problems in these application areas. MATLAB provides a number of features for documenting and sharing your work. You can integrate your MATLAB code with other languages and applications, and distribute your MATLAB algorithms and applications. Features include: High-level language for technical computing Development environment for managing code, files, and data Interactive tools for iterative exploration, design, and problem solving Mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, and numerical integration 2-D and 3-D graphics functions for visualizing data Tools for building custom graphical user interfaces Functions for integrating MATLAB based algorithms with external applications and languages, such as C, C++, Fortran, Java, COM, and Microsoft Excel

Starting and Quitting the MATLAB Program


Starting a MATLAB Session
On Microsoft Windows platforms, start the MATLAB program by double-clicking the MATLAB shortcut your Windows desktop. on

When you start MATLAB, by default, MATLAB automatically loads all the program files provided by MathWorks for MATLAB and other MathWorks products. You do not have to start each product you want to use. There are alternative ways to start MATLAB, and you can customize MATLAB startup. For example, you can change the folder in which MATLAB starts or automatically execute MATLAB statements upon startup.

The Desktop
When you start MATLAB, the desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with MATLAB.

Quitting the MATLAB Program


To end your MATLAB session, select File > Exit MATLAB in the desktop, or type quit in the Command Window. You can run a script file named finish.m each time MATLAB quits that, for example, executes functions to save the workspace.

Fundamental Expressions/Operations
MATLAB uses conventional decimal notion, builds expressions with the usual arithmetic operators and precedence rules: x = 3.421 x= 3.4210

y = x+8.2i y= 3.4210 + 8.2000i

z = sqrt(y) z= 2.4805 + 1.6529i

p = sin(pi/2) p= 1

Matrices and Magic Squares


In the MATLAB environment, a matrix is a rectangular array of numbers. Special meaning is sometimes attached to 1-by-1 matrices, which are scalars, and to matrices with only one row or column, which are vectors. 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. The operations in MATLAB are designed to be as natural as possible. Where other programming languages work with numbers one at a time, MATLAB allows you to work with entire matrices quickly and easily.

Entering Matrices
The best way for you to get started with MATLAB is to learn how to handle matrices. Start MATLAB and follow along with each example. You can enter matrices into MATLAB in several different ways: Enter an explicit list of elements. Load matrices from external data files. Generate matrices using built-in functions. Create matrices with your own functions and save them in files.

You only have to follow a few basic conventions: Separate the elements of a row with blanks or commas. Use a semicolon, ; , to indicate the end of each row. Surround the entire list of elements with square brackets, [ ].

Matrix Operations
Matrix operations are fundamental to MATLAB. Within a matrix, columns are separated by space, and the rows are separated by semicolon;. For example A = [1 2 3; 4 5 6; 7 8 9] A= 1 4 7 2 5 8 3 6 9

B = ones(3,3) B= 1 1 1 A+B ans = 2 5 8 3 6 9 4 7 10 1 1 1 1 1 1

A' ans = 1 2 3 4 5 6 7 8 9

The following matrix operations are available in MATLAB: + * / addition matrix multiplication ^ transpose right division power \ left division subtraction

The operations, , ^, \, and /, can be made to operate entry-wise by preceding them by a period.

Building Matrix
Convenient matrix building functions are eye identity matrix ones matrix of ones triu rand A = eye(3) A= 1 0 0 0 1 0 0 0 1 upper triangular part of a matrix randomly generated matrix zeros matrix of zeros diag tril diagonal matrix lower triangular part of a matrix

B = zeros(3,2) B= 0 0 0 0 0 0

C = rand(3,1) C= 0.9501 0.2311

0.6068 Matrices can be built from blocks. For example, D = [A B C D] D= 1.0000 0 0 0 0 0 0 0 0 0 0 0 0.9501 0.2311 0.6068

1.0000 0

1.0000

Retrieving part or an element of a matrix D(:,6) ans = 0.9501 0.2311 0.6068

D(1, :) ans = 1.0000 0 0 0 0 0.9501

D(1,6) ans = 0.9501 Other functions for colon notation: E = 0.3:0.4:1.5 E= 0.3000 0.7000 1.1000 1.5000

Vector Functions
Certain functions in MATLAB are vector functions, i.e., they operate essentially on a vector (row or column). For example, the maximum entry in a matrix D is given by max(max(D)). max(D) ans = 1.0000 1.0000 1.0000 0 0 0.9501

max(max(D)) ans = 1

A few of these functions are: max, min, sort, sum, prod, mean, std, any, all.

Matrix functions
The most useful matrix functions are eig inv size eigenvalues and eigenvectors inverse size svd det rank singular value decomposition determinant rank

For example F = rand(3,3) F= 0.4860 0.8913 0.7621 eig(F) ans = 1.7651 0.0310 -0.4997 rank(F) ans = 3 inv(F) ans = 17.9446 -0.1385 -9.9689 8.6579 -1.6802 -3.5560 -26.2485 1.8760 14.5444 0.4565 0.0185 0.8214 0.4447 0.6154 0.7919

The Colon Operator


The colon, :, is one of the most important MATLAB operators. It occurs in several different forms. The expression 1:10 is a row vector containing the integers from 1 to 10: 1 2 3 4 5 6 7 8 9 10

To obtain nonunit spacing, specify an increment. For example, 100:-7:50 is 100 93 86 79 72 65 58 51

and 0:pi/4:pi is 0 0.7854 1.5708 2.3562 3.1416

Subscript expressions involving colons refer to portions of a matrix: F(1:k,j) is the first k elements of the jth column of A. Thus: sum(F(1:3,3)) computes the sum of the fourth column. However, there is a better way to perform this computation. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. Thus: sum(F(:,end)) Determinant: Inverse: d = det(A) c=inv(A)

Arrays
When they are taken away from the world of linear algebra, matrices become two-dimensional numeric arrays. Arithmetic operations on arrays are done element by element. This means that addition and subtraction are the same for arrays and matrices, but that multiplicative operations are different. MATLAB uses a dot, or decimal point, as part of the notation for multiplicative array operations. The list of operators includes: + .* .\ .' Addition Element-by-element multiplication Element-by-element left division Unconjugated array transpose ./ .^ Subtraction

Element-by-element division Element-by-element power

Relational Operators
Relational operators compare operands quantitatively, using operators like "less than" and "not equal to." The following table provides a summary. For more information, see the relational operators reference page. < Less than > Greater than == Equal to <= >= ~= Less than or equal to Greater than or equal to Not equal to

Relational Operators and Arrays


The MATLAB relational operators compare corresponding elements of arrays with equal dimensions. Relational operators always operate element-by-element. In this example, the resulting matrix shows where an element of A is equal to the corresponding element of B. A = [2 7 6;9 0 5;3 0.5 6]; B = [8 7 0;3 2 5;4 -1 7]; A == B

ans = 0 0 0 1 0 0 0 1 0

For vectors and rectangular arrays, both operands must be the same size unless one is a scalar. For the case where one operand is a scalar and the other is not, MATLAB tests the scalar against every element of the other operand. Locations where the specified relation is true receive logical 1. Locations where the relation is false receive logical 0.

Logical Operators
MATLAB offers three types of logical operators and functions: Element-wise operate on corresponding elements of logical arrays. Bit-wise operate on corresponding bits of integer values or arrays. Short-circuit operate on scalar, logical expressions. The values returned by MATLAB logical operators and functions, with the exception of bit-wise functions, are of type logical and are suitable for use with logical indexing. Element-Wise Operators and Functions The following logical operators and functions perform elementwise logical operations on their inputs to produce a like-sized output array.The examples shown in the following table use vector inputs A and B, where A = [0 1 1 0 1]; B = [1 1 0 0 1];
Op erator & Description Example

Returns 1 for every element location that is true (nonzero) in both arrays, and 0 for all other elements. Returns 1 for every element location that is true (nonzero) in either one or the other, or both arrays, and 0 for all other elements. Complements each element of the input array, A. Returns 1 for every element location that is true (nonzero) in only one array, and 0 for all other elements.

A & B = 01001 A | B = 11101 ~A = 10010 xor(A,B) = 10100

~ xor

For operators and functions that take two array operands, (&, |, and xor), both arrays must have equal dimensions, with each dimension being the same size. The one exception to this is where one operand is a scalar and the other is not. In this case, MATLAB tests the scalar against every element of the other operand.

Operator Overloading
You can overload the &, |, and ~ operators to make their behavior dependent upon the class on which they are being used. Each of these operators has a representative function that is called whenever that operator is used. These are shown in the table below.

Logical Operation Equivalent Function A & B A | B ~A and(A, B) or(A, B) not(A)

Short-Circuit Operators
The following operators perform AND and OR operations on logical expressions containing scalar values. They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.
Operator Description && || Returns logical 1 (true) if both inputs evaluate to true, and logical 0 (false) if they do not. Returns logical 1 (true) if either input, or both, evaluate to true, and logical 0 (false) if they do not.

The statement shown here performs an AND of two logical terms, A and B: A && B If A equals zero, then the entire expression will evaluate to logical 0 (false), regardless of the value of B. Under these circumstances, there is no need to evaluate B because the result is already known. In this case, MATLAB short-circuits the statement by evaluating only the first term. A similar case is when you OR two terms and the first term is true. Again, regardless of the value of B, the statement will evaluate to true. There is no need to evaluate the second term, and MATLAB does not do so.

Operator Precedence
You can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence levels determine the order in which MATLAB evaluates an expression. Within each precedence level, operators have equal precedence and are evaluated from left to right. The precedence rules for MATLAB operators are shown in this list, ordered from highest precedence level to lowest precedence level:

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

Parentheses () Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^) Unary plus (+), unary minus (-), logical negation (~) Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\) Addition (+), subtraction (-) Colon operator (:) Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) Element-wise AND (&) Element-wise OR (|) Short-circuit AND (&&) Short-circuit OR (||)

Multivariate Data
MATLAB uses column-oriented analysis for multivariate statistical data. Each column in a data set represents a variable and each row an observation. The (i,j)th element is the ith observation of the jth variable. For five observations, the resulting array might look like

D=

[ 72 81 69 82 75

134 201 156 148 170

3.2 3.5 7.1 2.4 1.2 ]

The first row contains the heart rate, weight, and exercise hours for patient 1, the second row contains the data for patient 2, and so on. Now you can apply many MATLAB data analysis functions to this data set. For example, to obtain the mean and standard deviation of each column, use mu = mean(D), mu = 75.8 sigma = 5.6303 25.499 2.2107 161.8 3.48 sigma = std(D)

The format Function


The format function controls the numeric format of the values displayed. The function affects only how numbers are displayed, not how MATLAB software computes or saves them. Here are the different formats, together with the resulting output produced from a vector x with components of different magnitudes. x = [4/3 1.2345e-6] format short: format short e: format short g: format long: format long e: format long g: format bank: format rat: format hex: 1.3333 0.0000 1.3333e+000 1.2345e-006 1.3333 1.2345e-006 1.33333333333333 0.00000123450000 1.333333333333333e+000 1.234500000000000e-006 1.33333333333333 1.2345e-006 1.33 4/3 0.00 1/810045

3ff5555555555555 3eb4b6231abfd271

M-files
MATLAB can execute a sequence of statements in a file. Such files are called M-files because they must have the file type of .m as the last part of their filename. There are two types of M -files: script files and function files. Script files A script file consists of a sequence of normal MATLAB statements. For example, type all the commands for generating the figure into a single script file and save as sineplot.m. Then the MATLAB command sineplot will cause the statements in the file to be executed. Try it.

10

Function files You can create new functions specific to your problem, which will then have the same status as other MATLAB functions. Variables in a function files are by default local, otherwise need to be declared as global. The function file will start with function *y1, y2, ..+ = Function Name (x1, x2, ) Here is a simple example. The file myrand.m contains the statements function x = myrand(l, u, row, col) % generate uniformly-distributed random number matrix (row, col) between low% bound l and upper-bound u. x = l + rand(row, col).* (u-l); We would like to generate a 2 by 3 random matrix between 1.5 and 4.5 a = myrand(1.5, 4.5, 2, 3) a= 4.2654 3.7146 2.0288 2.7171 4.3064 4.2507

Programming
Flow Control if, else, and elseif
if expression, statements, end evaluates expression and, if the evaluation yields logical 1 (true) or a nonzero result, executes one or more MATLAB commands denoted here as statements. expression is a MATLAB expression, usually consisting of variables or smaller expressions joined by relational operators (e.g., count < limit), or logical functions (e.g., isreal(A)). Simple expressions can be combined by logical operators (&&, ||, ~) into compound expressions such as the following. MATLAB evaluates compound expressions from left to right, adhering to operator precedence rules. (count < limit) && ((height - offset) >= 0) Nested if statements must each be paired with a matching end. The if function can be used alone or with the else and elseif functions. When using elseif and/or else within an if statement, the general form of the statement is if expression1 statements1 elseif expression2 statements2 else statements3 end

11

See Program Control Statements in the MATLAB Programming Fundamentals documentation for more information on controlling the flow of your program code. Within the context of an if or while expression, MATLAB does not necessarily evaluate all parts of a logical expression. In some cases it is possible, and often advantageous, to determine whether an expression is true or false through only partial evaluation. For example, if A equals zero in statement 1 below, then the expression evaluates to false, regardless of the value of B. In this case, there is no need to evaluate B and MATLAB does not do so. In statement 2, if A is nonzero, then the expression is true, regardless of B. Again, MATLAB does not evaluate the latter part of the expression. 1) if (A && B) 2) if (A || B)

You can use this property to your advantage to cause MATLAB to evaluate a part of an expression only if a preceding part evaluates to the desired state. Here are some examples. while (b ~= 0) && (a/b > 18.5) if exist('myfun.m') && (myfun(x) >= y) if iscell(A) && all(cellfun('isreal', A)) Empty Arrays In most cases, using if on an empty array treats the array as false. There are some conditions however under which if evaluates as true on an empty array. Two examples of this, where A is equal to [], are if all(A), do_something, end if 1|A, do_something, end The latter expression is true because of short-circuiting, which causes MATLAB to ignore the right side operand of an OR statement whenever the left side evaluates to true.

else
if expression, statements1, else statements2, end evaluates expression and, if the evaluation yields logical 1 (true) or a nonzero result, executes one or more MATLAB commands denoted here as statements1 or, if the evaluation yields logical 0 (false), executes the commands in statements2. else is used to delineate the alternate block of statements.. A true expression has either a logical 1 (true) or nonzero value. For nonscalar expressions, (for example, "if (matrix A is less than matrix B)"), true means that every element of the resulting matrix has a true or nonzero value. Expressions usually involve relational operations such as (count < limit) or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as (count < limit) & ((height - offset) >= 0). See Program Control Statements in the MATLAB Programming Fundamentals documentation for more information on controlling the flow of your program code.

elseif if expression1, statements1, elseif expression2, statements2, end evaluates expression1 and, if the evaluation yields logical 1 (true) or a nonzero result, executes one or more MATLAB commands denoted here as statements1. If expression1 is false, MATLAB evaluates the elseif expression, expression2. If expression2 evaluates to true or a nonzero result, executes the commands in statements2. A true expression has either a logical 1 (true) or nonzero value. For nonscalar expressions, (for example, is matrix A less then matrix B), true means that every element of the resulting matrix has a true or nonzero value.

12

Expressions usually involve relational operations such as (count < limit) or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as (count < limit) & ((height - offset) >= 0). See Program Control Statements in the MATLAB Programming Fundamentals documentation for more information on controlling the flow of your program code. The commands else and if, with a space or line break between them, differ from elseif, with no space. The former introduces a new, nested if that requires a matching end statement. The latter is used in a linear sequence of conditional statements with only one terminating end. The two segments shown below produce identical results. Exactly one of the four assignments to x is executed, depending upon the values of the three logical expressions, A, B, and C. if A x=a else if B x=b else if C x=c else x=d end end end end else x=d elseif C x=c elseif B x=b if A x=a

for for index = values program statements : end repeatedly executes one or more MATLAB statements in a loop. values has one of the following forms: initval:endval increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval. initval:step:endval is negative. increments index by the value step on each iteration, or decrements when step

valArray creates a column vector index from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :). To force an immediate exit of the loop, use a break or return statement. To skip the rest of the instructions in the loop, increment the loop counter, and begin the next iteration, use a continue statement.

13

Avoid assigning a value to the index variable within the body of a loop. The for statement overrides any changes made to the index within the loop. To iterate over the values of a single column vector, first transpose it to create a row vector. Examples: Create a Hilbert matrix using nested for loops: k = 10; hilbert = zeros(k,k); for m = 1:k for n = 1:k hilbert(m,n) = 1/(m+n -1); end end Step by increments of -0.1, and display the step values: for s = 1.0: -0.1: 0.0 disp(s) end % Preallocate matrix

Execute statements for a defined set of index values: for s = [1,5,8,17] disp(s) end Successively set e to unit vectors: for e = eye(5) disp('Current value of e:') disp(e) end

Here is an example showing if, else, and elseif. for m = 1:k for n = 1:k if m == n a(m,n) = 2; elseif abs(m-n) == 2 a(m,n) = 1; else

14

a(m,n) = 0; end end end For k=5 you get the matrix a= 2 0 1 0 0 0 2 0 1 0 1 0 2 0 1 0 1 0 2 0 0 0 1 0 2

While
while expression program statements : end repeatedly executes one or more MATLAB program statements in a loop, continuing until expression no longer holds true or until MATLAB encounters a break, or return instruction, thus forcing an immediate exit of the loop code. If MATLAB encounters a continue statement in the loop code, it interrupts execution of the loop code at the location of the continue statement, and begins another iteration of the loop at the while expression statement. expression is a MATLAB expression that evaluates to a result of logical 1 (true) or logical 0 (false). expression can be scalar or an array. It must contain all real elements, and the statement all(A(:)) must be equal to logical 1 for the expression to be true. expression usually consists of variables or smaller expressions joined by relational operators (e.g., count < limit) or logical functions (e.g., isreal(A)). Simple expressions can be combined by logical operators (&&, ||, ~) into compound expressions such as the following. MATLAB evaluates compound expressions from left to right, adhering to Operator Precedence rules. (count < limit) && ((height - offset) >= 0) statements is one or more MATLAB statements to be executed only while the expression is true or nonzero. The scope of a while statement is always terminated with a matching end. Examples The variable eps is a tolerance used to determine such things as near singularity and rank. Its initial value is the machine epsilon, the distance from 1.0 to the next largest floating-point number on your machine. Its calculation demonstrates while loops. eps = 1; while (1+eps) > 1 eps = eps/2;

15

end eps = eps*2 This example is for the purposes of illustrating while loops only and should not be executed in your MATLAB session. Doing so will disable the eps function from working in that session.

Data Import and Export


File Opening, Loading, and Saving Text Files Spreadsheets Low-Level File I/O Images Scientific Data Audio and Video XML Documents Memory Mapping File Name Construction File Compression Internet File Access Open files; transfer data between files and MATLAB workspace Delimited or formatted I/O to text files Excel and Lotus 1-2-3 files Read and write operations at the byte or character level Graphics files CDF, FITS, HDF formats Read and write audio and video, record and play audio Documents written in Extensible Markup Language Access file data via memory map using MATLAB array indexing Get path, directory, filename information; construct filenames Extract from tar or zip file; compress and decompress files Send e-mail, download from URL, or connect to FTP server

File Opening, Loading, and Saving


daqread importdata load open save uigetdir uigetfile uiimport uiputfile uisave winopen Read Data Acquisition Toolbox (.daq) file Load data from file Load data from MAT-file into workspace Open file in appropriate application Save workspace variables to file Open standard dialog box for selecting directory Open standard dialog box for retrieving files Open Import Wizard to import data Open standard dialog box for saving files Interactively save workspace variables to MAT-file Open file in appropriate application (Windows)

16

Text Files
csvread csvwrite dlmread dlmwrite fileread textread textscan type Read comma-separated value file Write comma-separated value file Read ASCII-delimited file of numeric data into matrix Write matrix to ASCII-delimited file Read contents of file into string Read data from text file; write to multiple outputs Read formatted data from text file or string Display contents of file

Microsoft Excel
xlsfinfo xlsread xlswrite Determine whether file contains Microsoft Excel spreadsheet Read Microsoft Excel spreadsheet file Write Microsoft Excel spreadsheet file

Plotting Figures
Creating a Figure If y is a vector, plot (y) produces a linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. t = 0:pi/100:2*pi; x = sin(t); y1 = sin(t+0.25); y2 = cos(t-0.25); figure(1) % open a figure and make it current, not necessarily plot(x,y1,'r-',x,y2, 'g--') title('sin-cos plots') xlabel('x=sin(t)') ylabel('y') By plotting multiple figures on the graph, one alternative way is to use hold on and hold off commands, plot(x,y1, 'r-') hold on plot(x,y2, 'g--') hold off

17

Other types of plots: loglog semilogx semilogy plot using logarithmic scales for both axes plot using a logarithmic scales for x-axis and linear scale for the y-axis figure out yourself

Line styles, markers, and color Symbol y m c r g b w k Color yellow magenta cyan red green blue white black Symbol . o x + * : -. -Exporting a Figure 1) Cut and paste: click Edit at the top menu bar of the figure window, then click Copy Figure, paste the figure wherever you want. 2) Save as a file: print tiff deps (print as a postscript file). Type help print to find out more options. The MATLAB hold command enables you to add plots to an existing graph. When you type hold on Now MATLAB does not replace the existing graph when you issue another plotting command; it adds the new data to the current graph, rescaling the axes if necessary. For example, these statements first create a contour plot of the peaks function, then superimpose a pseudocolor plot of the same function: [x,y,z] = peaks; pcolor(x,y,z) shading interp hold on contour(x,y,z,20,'k') hold off The hold on command combines the pcolor plot with the contour plot in one figure. Linestyle point circle x-mark plus star solid dotted dashdot dashed

18

3D plotting
When you make a 3-dimensional plot, you usually have a z variable that is a function of both x and y. When you want x and y to vary over some range, you need a matrix (rather than a vector) for x and y to get a complete domain that covers all the different combinations of those x and y values over some range. A function called meshgrid will set up x and y matrixes like this for you. The x matrix varies the x down rows and keeps it constant in columns, and the y matrix varies the y in columns and keeps it constant across rows, so you get all combinations of x and y if you use the two matrices. To get a rectangular domain that goes from x=1 to x=10 in steps of .5, and from y=1 to y=10 in steps of .5 using meshgrid, you can use [x, y] = meshgrid([1:.5:10],[1:.5:10]); Then, you can do a 3d plot by caculating some z values on the x and y domains, and doing a surface, mesh, or contour plot. z = x.^2 - y.^2 surf(x,y,z) mesh(x,y,z) contour(x,y,z) You could also use surfc or meshc to get surface or mesh plots with a contour plot drawn on the x-y plane. Surface plots and mesh plots color the plots according to the z value, by default. You can use some other equallysized matrix to get the coloring instead by adding that matrix as an extra argument, like: c = x.^2 + y.^2; mesh(x,y,z,c)

Bar Charts
2D bar graphs plot data points in terms of their area. Given some random data: xBar=[1:10]; yBar=rand(1,10) * 100; a bar chart is produced using: bar(xBar,yBar); 2D bar charts can also be created for matrices, in which case each row in the matrix is considered as one group of bars. The resulting graph distinguishes matrix columns with different colors. yBar=rand(7,3); bar(yBar); 3D bar graphs are easily obtained from matrices as well, using the bar3 command: bar3(yBar)

Meshing (3d graphs)


3D graphs are generated using the function mesh or surf . Given a 2D matrix of values, each value is used as a z-value (elevation), and placed in a 3D view. Given a function of sine and cosine:

19

z=[]; for i=1:100 for j=1:100 z(i,j) = sin(i/10) + cos(j/10); end end mesh(z); creates a mesh (with holes) next command creates a mesh with filled patches (a surface). surf(z); For the data set of gasoline prices per region, a viable mesh would be: mesh(data);

Multiple plots
Using the subplot function, it is possible to generate separate plots in a grid of figures. SUBPLOT(M, N, P) creates a grid of figures for M rows, N columns, and fills the Pth cell with the next figure. Example: subplot(3, 2, 1), plot(rand(1, 10)); subplot(3, 2, 2), bar(rand(1, 10)); subplot(3, 2, 3), surf(rand(20)); subplot(3, 2, 4), hist(rand(50)); subplot(3, 2, 5), plot(sin([0:0.1:10])); subplot(3, 2, 6), plot(rand(1,100),'gd:');

20

You might also like