28
pág 1 de 28 Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with arrays. In this way, the name is an abbreviation of MATrix LABoratory. The program always works with matrices, treating the numbers as arrays of dimension (1x1). In this tutorial a brief overview on some basic useful aspects with relation to the Computational Fluid Dynamics subject imparted in the Master in Water Engineering is given. In each point some considerations after the symbol • are included. Index 11._Working environment ………………………………………………………………………1 12._Basic operations ……………………………………………………………………………2 13._Basic operations for arrays …………………………………………………………………3 14._Operations with the structure of the arrays …………………………………………………6 15._Representation of the results through graphics ……………………………………………8 16._Other representations………………………………………………………………………11 17._Scripts and functions ……………………………………………………………………14 18._Loops ……………………………………………………………………………………18 19._Conditional statements ……………………………………………………………………19 10._Input and output files ……………………………………………………………………22 1. Working environment In the main MATLAB window it is possible to see: The command window, in which the commands are written directly. The window is cleared writing in the command window: clc The workspace, in which the variables created with the last value saved appear. By double clicking on each one, another window will be open with this value. The variables will not appear (the memory is cleared) writing in the command window: clear The command history which has the information of all the commands written in the command window. The current folder bar where the folder (or directory) where MATLAB works can be selected, which has no importance when functions or scripts are not used. The current folder window shows the files contained in the current folder, allowing copying or deleting of files and is also a valid place to select the path.

Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

Embed Size (px)

Citation preview

Page 1: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 1 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with arrays. In this way, the name is an abbreviation of MATrix LABoratory. The program always works with matrices, treating the numbers as arrays of dimension (1x1). In this tutorial a brief overview on some basic useful aspects with relation to the Computational Fluid Dynamics subject imparted in the Master in Water Engineering is given. In each point some considerations after the symbol • are included. Index 11._Working environment ………………………………………………………………………1 12._Basic operations ……………………………………………………………………………2 13._Basic operations for arrays …………………………………………………………………3 14._Operations with the structure of the arrays …………………………………………………6 15._Representation of the results through graphics ……………………………………………8 16._Other representations………………………………………………………………………11 17._Scripts and functions ……………………………………………………………………14 18._Loops ……………………………………………………………………………………18 19._Conditional statements ……………………………………………………………………19 10._Input and output files ……………………………………………………………………22 1. Working environment In the main MATLAB window it is possible to see:

The command window, in which the commands are written directly. The window is cleared writing in the command window: clc

The workspace, in which the variables created with the last value saved appear. By double clicking on each one, another window will be open with this value. The variables will not appear (the memory is cleared) writing in the command window: clear

The command history which has the information of all the commands written in the command window.

The current folder bar where the folder (or directory) where MATLAB works can be selected, which has no importance when functions or scripts are not used. The current folder window shows the files contained in the current folder, allowing copying or deleting of files and is also a valid place to select the path.

Page 2: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 2 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

2. Basic operations Operations can be rapidly done in the command window as in a typical calculator. Following this, the way to write some operations is pointed out: Using different symbols: ^ / * + - .

Operation: 52 1 3

0,25 3 (1 3)

Write: (2^5+1/3)/(0.25-3*(1-3^0.5)) Value: 13.218

• 0.5 = .5 • It appears in the workspace: ans • It appears in the command history (always happens): the command written • It can be used as variable in later operations: ans • One command written can be recovered both by dragging (pressing and holding the button while moving the mouse) the command from the command history, and by pressing the arrow keys (pressing up as many times as commands were written since the desirable command was written). Using defined constants and intrinsic/defined functions: pi sin()

Operation: sin(pi) Write: A=sin(pi) Value: 0.0

• It appears in the workspace (now a name is put): A • It can be used as variable in later operations: A, ans • Information about the variables can be printed by writing in the command window: whos • Do not give a variable name the same as one of the defined constants or the value will be lost. Also, the saved variables can be lost. • Other constants and functions: eps as the constant that defines the smallest positive number that can be added to 1 and produce a result larger than 1, cos() as the cosine function, tan () as the tangent function, exp () as the exponential function, abs() as the absolute value function,… • The error for the double precision variables (always used by MATLAB), which is defined with the eps constant, is observed: precision of approximately 16 digits. Using different formats to print the results and the symbol to avoid repetition: long short rat ;

Example: format long Write: format long Value: 1.224646799147353e-016 A Example: format rat Write: format rat Value: -- A;

• Set the preferred format. • Use semicolons when the returned value is not necessary. The format rat allows the results to be printed in a rational way. Using the help command: help

Example: format Write: help format

• Information about any command can obtained following the structure pointed out. • In MATLAB there is a lot of information about any command that will be avoided in this short tutorial.

Page 3: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 3 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

3. Basic operations for arrays Arrays, which are matrices or vectors, will be dealt with first. Before this step, the clc and clear commands are used to clear the command window and the workspace. Using the array notation to generate it: [, ; ,]

Row array: (2 3 0 1) Write: a=[2 3 0 1]; Dimension: (1x4)

Column array:

2301

Write: b=[2;3;0;1]; Dim: (4x1)

Matrix:

0 1 3 22 1 7 23 0 6 35 0 10 5

Write: A=[0 -1 3 2;2 1 7 2;3 0 6 3;5 0 10 -5]; Dim: (4x4)

• The structure of the matrix keeps the same structure for columns and rows as the vectors. • It is the same to write the rows with commas: [2 3 0 1] = [2,3,0,1] • MATLAB differentiates capital letters and lowercase. In order to check it, write first: a • Now write: A Using basic operations with arrays: Consider two arrays, the first with dimensions (mxn) and the second with dimensions (mmxnn)

1. First array plus second array (restriction: mm=m, nn=n): A+A Write: A+A Dim: (mxn) 2. A constant times the first array (without restriction): 2 A Write: 2*A Dim: (mxn)

• The first two operations give the same result, logically.

3. First array times second array (restriction: n=mm): a A Write: a*A Dim: (mxnn) 4. First array elevated to a constant number (restriction: m=n): 2A Write: A^2 Dim: (nxn)

• The last operation must be done in square matrices as the restriction indicates. This is a product of matrices as in the third operation, and the restriction is the same.

5. First array divided by second array (restriction: m=mm): -1A b Write: A\b Dim: (nn,n)

• This operation appears when solving algebraic systems (Ax=b). The restriction has the same meaning as in the third operation. The command mldivide(A,b) leads to the same. The operation A/b would lead to -1bA which is not available in this case.

6. Transpose array of the first (without restriction): b' Write: b' Dim: (nxm)

Page 4: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 4 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

Values of the previous examples:

0 2 6 4 17 1 31 3 1.6334 2 14 4 33 1 75 17 0.400

1.2. 3. 11 1 37 5 4. 5. 6 0 12 6 33 3 75 9 0.866

10 0 20 10 5 5 25 65 0.100

6. 2 3 0 1 Using defined arrays:

1. Diagonal array of the first (without restriction in dimensions): Write: c=diag(A) Dim: (min(m,n)x1) if matrix, (max(m,n)xmax(m,n)) if vector

• If the array is a matrix, the diagonal coefficients will be considered building a column vector with these coefficients of the way aii. If the array is a vector, the opposite process is done, building a matrix which diagonal coefficients will be that of the vector.

2. Random matrix (generated with random coefficients): Write: rand(3), rand(2,4) Dims: (3x3), (2x4)

• The notation (m) is for square matrices and is the same as (m,m). • More than one expression can be put in the same line. Every expression followed by a comma (in the last one not necessary) will be printed, and every expression followed by semicolons will not be printed. Again, the user will decide what to do.

3. Matrix of zeros (every coefficient is null) and matrix of ones (every coefficient is equal to one): Write: zeros(1,7), ones(2) Dims: (1x7), (2x2)

4. Identity matrix (or unit matrix): Write: B=eye(4) Dim: (4x4) Values of the previous examples:

0 1 0 0 01 1 1 0 1 0 0

1. 2. 3. 0 0 0 0 0 0 0 4. 6 1 1 0 0 1 05 0 0 0 1

Using commands to know array features: sum rank size numel lenght

Sum of the coefficients of the array: Write: sum(a) Dim: (1xn) if matrix, (1x1) if vector Rank of the array obtaining the minimum between m and n Write: rank(A) Dim: (1x1) Dimension of the array obtaining m and n Write: size(A) Dim: (1x2)

• If the array is a matrix, the sum of the coefficients of each column will be done. If the array is a vector, the sum of all the coefficients is done. In the array used will do 2+3+0+1. • The total number of coefficients of the array, which is mxn, can be obtained directly from the next expression: numel(A)

Page 5: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 5 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

• The next command only gives the n number of coefficients of each row of an array: length (A) Using coefficient by coefficient array operations: .* .^ ./ .\

1. Coefficients of the first array times coefficients of the second (restriction: m=mm, n=nn): Write: A.*B Dim: (mxn)

2. Coefficients of the first array which are elevated to a number (without restriction): Write: A.^4 Dim: (mxn)

3. Coefficients of the first array which are elevated to the coefficients of the second (restriction: the same as before): Write: A.^B Dim: (mxn)

4. Coefficients of the first array divided by coefficients of the second (restriction: the same as before): Write: A./B Dim: (mxn)

• The coefficients of A are divided by the coefficients of B. Here A./B=B.\A. 5. This type of operations is useful when a repetitive operation has to be done. For example, in order to evaluate the function y=tan3(ln(x)) in the values (in radians) x=1, 1,5, 2,5, 3,5, 4 write: x=[1, 1.5, 2.5, 3.5, 4]; y= tan(log(x)).^3

• The array product (without the point) would be impossible. Above, some expressions could be calculated without the point leading to different solutions. • Any function can be applied to an array in such a way that all the coefficients are affected. For example: sin (A), exp (A), log(A), log10(A) • When a trigonometric function command ends in “d” the argument must be in degrees. For example: sind(x), tand(x),… being sind(x*180/pi)=sin(x) • The natural logarithm (the logarithm to base e) is written: log() Values of the previous examples:

0 0 0 0 0 1 81 16 0 1 1 1 00 1 0 0 16 1 2401 16 1 1 1 1 1

1. 2. 3. 4. 0 0 6 0 81 0 1296 81 1 1 6 1 60 0 0 5 625 0 10000 625 1 1 1 5 5

NanNan

5. 0 0.079 2.213 28.027 153.849

Page 6: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 6 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

4. Operations with the structure of the arrays Using notation for obtaining coefficients: ( , ) ( ,:) ( , : ) ( ,[ ])

1. Coefficient located in the second row and the fourth column: Write: A(2,4) Dim: (1x1)

2. Coefficients located in the second row: Write: A(2,:) Dim: (1xn) 3. Coefficients located in the fourth column: Write: A(:,4) Dim: (mx1)

4. Coefficients located in a part of the second row between b1=1 and b2=3 (bounds included): Write: A(2,1:3) Dim: (1x(b2-b1)) 5. Coefficients located in a part of the third column between b1=1 and b2=4 (bounds included): Write: A(1:4,3) Dim: ((b2-b1)x1)

• A(1:4,3)=A(:,3). • A sub-matrix of another can be obtained with this last procedure. For example: A(1:2,1:3) will give a matrix with dimensions (2x3).

6. Coefficients located in a part of the second row in such a way that they are not correlative, such as b1=1, b2=4. Write: A(2,[1 4]) Dim: (1xi)

• The same procedure can be follow for columns, or for rows and columns at the same time. Values of the previous examples:

2 32 7

1. 2 2. 2 1 7 2 3. 4. 2 1 7 5. 6. 2 2 3 65 10

Using combination of arrays: [array;array] [array,array] []

1. Array added after the last row of the second array (restriction: n=nn): Write: G=[A; 1 0 1 1]; Dim: ((m+mm)xn)

• Remember that this is the same to write G=[A;1,0,1,1]; and A is not rewritten with this procedure. • The array can be added before the first row doing G=[1 0 1 1;A], or can be between rows of A using the commands already indicated in the before 1, 2, 3, 4 and 5 points. For example G= G=[A(1:2,:);1,0,1,1;A(3:4,:)] will locate the row at the middle.

2. Array added after the last column of the second array (restriction: m=mm): Write: G=[A c] Dim: (mx(n+nn))

• To write the variable name (in where the array is saved) is the same as writing it directly. • The array can be put in any position. • Remember that this is the same to write G=[A,c]

Page 7: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 7 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

3. Column removed from the array: Write: G(:,3)=[] Dim: (mx(n-1))

• Remember that G is rewritten from the last array (as ans did so many times). • Any column or row can be removed considering the commands already indicated in the before 1, 2, 3, 4 and 5 points. For example A=[a;A;a] will rewrite A obtaining a (6x4) array, and A([1 6],:)=[] will remove just the added columns recovering the original A. • Vectors can be written in an abbreviate way, allowing for all this type of operations. The next two expressions separated by slash generate the same result: b=[1;2;3;4]; b(:,1)=b(:,1)*2; b(3,:)=[] / b=[1;2;3;4]; b(:)=b(:)*2; b(3)=[] Values of some previous examples:

0 1 3 2 0 0 1 2 02 1 7 2 1 2 1 2 1

2. 3. 3 0 6 3 6 3 0 3 65 0 10 5 5 5 0 5 5

Page 8: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 8 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

5. Representation of the results through graphics Using values equally spaced in arrays: : linspace()

1. Writing values between b1=1 and b2=2 with a space sp=0.5: Write: 1:.5:5 Dim: (1,9)

• This procedure avoids writing the array coefficient by coefficient if they are equally spaced. • If the space is the unit, this is not necessary to write it. For example, write: 1:5

2. Writing values between b1=-5 and b2=5 with 21 subdivisions: Write: linspace(-5,5,21) Dim: (1,21)

• If the number of subdivisions and the space are well chosen both methods give the same result. In this way -5:0.5:5=linspace(-5,5,21). Using one of the commands so as to represent: plot

1. Plotting the continuous function y(x)=sin(x)-cos2(x) with plot: Write: x=-5:.5:5; y=sin(x)-cos(x).^2; plot (x,y)

A graphic window appears after that, showing the left figure in where the function cross the (x,y) points (written in the two arrays defined) with lines between them:

• A smaller space will let to obtain better accuracy as there are more discrete points. For example, using the arrow keys to recover the command and using a space of sp=0.05 the right figure is obtained. • The figure can be saved quickly (in .fig which is a MATLAB format) selecting File>Save, or can be saved in different formats (.jpg, .eps,…) by selecting File>Export in such a way that the user can choose the required option.

-5 0 5-1.5

-1

-0.5

0

0.5

1

-5 0 5-1.5

-1

-0.5

0

0.5

1

Page 9: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 9 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

2. Plotting the discrete function of the succession 1/n for n=1, 20 with plot: Write: n=1:20; m=1./n; plot (n,m, '.') Then, the left figure is obtained: • Add '.' as a representation with points is required for a discrete function. • Other features can be incorporated. For example, plot (n,m, 'o') will represent larger points (with ‘b’, blue lines will paint instead), axis tight adjust the graphic making the maximum zoom that let to represent all the points. On the other hand, xlabel=('x axis') will put the name x axis to the coordinate axis. In the same way ylabel=('y axis') will do the same for the ordinate axis. It is recommended to see the help for the plot command. The left figure is obtained writing: plot (n,m,'o'); axis tight; xlabel=('x axis'); ylabel('y axis'); • The features of the graphic can be easily changed from the graphic window (in File>generate code, the used commands can be seen).

3. Representation of the function y(x)=sin(x)-cos2(x) and z(x)=sin2(x) at the same time with plot: Write: z=sin(x).^2; plot(x,y,x,z); • The command hold on (hold off is working by default) let to keep the before representation in such a way that the same result (though in a single color) is obtained writing: hold on; plot(x,y); plot(x,z); • Since hold on is used all the graphics will be added unless hold off command is written.

0 5 10 15 200

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

2 4 6 8 10 12 14 16 18 20

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

y ax

is

Page 10: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 10 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

Using another command so as to represent: ezplot

The representation of graphics with the ezplot command is not based upon defined arrays (they are not needed). There are two ways of representation, explicitly or implicitly and the interval of representation could be indicated.

1. An explicit function of the type y(x) is written without including the dependent variable (just y(x)). So as to represent y(x)=e3cos(x)-1 it would be necessary to write (obtaining the below right figure): ezplot('exp(cos(3*x))-1') • MATLAB selects a view in which the function is seen. • The x interval could be given writing: ezplot('exp(cos(3*x))-1',[1,10]) • The y interval could be given too always followed by the x interval. So as to represent between x=1 and x=10, between y=2 and y=20 (in this case the function could not be seen) it is written: ezplot('exp(cos(3*x))-1',[1,10,2,20]).

2. In an implicit function of the type f(x,y) both variables are written in the command and the points that verify that f(x,y)=0 are represented (plane curves). This is necessary when the equation cannot be put as one of the before. In order to represent x3+y2-2xy+x-y=0 it would be valid to write (obtaining the above right figure): ezplot('x^3+y^2-2*x*y+x-y',[-4,4,-4,4]) • In explicit functions both procedures could be carried out. For example, ezplot('x') = ezplot('x-y').

x

y

x3+y2-2 x y+x-y = 0

-4 -3 -2 -1 0 1 2 3 4-4

-3

-2

-1

0

1

2

3

4

-6 -4 -2 0 2 4 6

-0.5

0

0.5

1

1.5

x

exp(cos(3 x))-1

Page 11: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 11 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

6. Other representations Using commands so as to represent meshes and vector fields (fx(x,y),fy(x,y), representation in the x-y plane): line quiver

1. Representation of closed triangular polygons with vertices in the points P1(1,0), P2(2,1), P3(2,2), P4(1,2), P5(0,1) so as to generate a mesh. Observing the points, one possible disposition which avoid the triangles share the same domain, could be that formed by the triangles P1P2P5, P2P4P5 and P2P3P4. The line command has to be used for each triangle once the coordinates of each one are generated separately writing: x=[1 2 2 1 0]; y=[0 1 2 2 1]; xt1=[x(1),x(2),x(5),x(1)]; yt1=[y(1),y(2),y(5),y(1)]; xt2=[x(2),x(4),x(5),x(2)]; yt2=[y(2),y(4),y(5),y(2)]; xt3=[x(2),x(3),x(4),x(2)]; yt3=[y(2),y(3),y(4),y(2)];

Now, the triangles can be created writing: line(xt1,yt1); line(xt2,yt2); line(xt3,yt3);

• A graphic window appears to see that. • The lines always will appear (though hold off is selected). • The line command needs that the first point is the last point so as to close polygon. The command establishes lines between the points following the order given.

2. Representation of velocity vectors u1=(0,5, 0,5), u2=(1, 0), u3=(1, 0), u4=(1, 0), u5=(0,5, 0,5) in the before points with quiver writing: u=[.5 1 1 1 .5]; v=[.5 0 0 0 .5]; quiver (x,y,u,v); • A new representation appears. The size of the arrows and the color can be changed written: quiver(x,y,u,v,.5, 'r'); Now, the mesh is repeated: line(xt1,yt1); line(xt2,yt2); line(xt3,yt3); Following this, so as to vertical axis and horizontal axis has the same scale, it is written (generating the below figure): axis equal

• The number added in quiver command indicates the increase or decrease of the arrows, in such a way that the number 2 implies that the size is twice that of the vector module.

0 0.5 1 1.5 2 2.50

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2

Page 12: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 12 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

Using another command so as to represent meshes: meshgrid

The generation of a rectangular element mesh is done. The grid could be defined in a regular way or not. A regular shape is obtained if x separation is constant and y separation is constant leading to the same element size too (uniform mesh). As a particular case, if x separation and y separation are the same, quadrangular elements are generated. In order to build a uniform quadrangular element mesh with a side of 2 m long, a space of sp=2 is considered. Considering the limits of the mesh in the lines x=b1=-2, x=b2=2, y=b3=-4 and y=b4=4 the next commands has to be written: rx=-2:2:2; ry=-4:2:4; [x,y]=meshgrid(rx,ry);

• A graphic representation does not appear but the elements are defined as when xt1, xt2, xt3, yt1, yt2 and yt3 where previously defined. • If rx=ry, it could be written: [x,y]=meshgrid (rx). • In this type of expressions as arrays as variables written inside [] are obtained. Using commands so as to represent scalar fields (surfaces, f(x,y), representation with a 3D view or in the x-y plane): surf contour

1. Representation of a function f(x,y), which will be a surface (as was explained, if f(x,y)=k, a plane curve will be generated as the third variable disappear). So as to represent the surface z=x2-5sin(xy)+y2 the next commands has to be written: z=x.^2-5*sin(x.*y)+y.^2; surf(x,y,z)

• A 3D graphic representation appears with surface in which the points (x,y,z) verify the function in such a way that the dependent variable appear drawn the vertical axis. • The coordinates of each point are in the x, y and z matrices, in coefficients at the same position. • The function is only evaluated in the points of the defined arrays (rx and ry). The function could not be directly represented through the vectors rx and ry (z=rx.^2-5*sin(rx.*ry)+ry.^2; surf(rx,ry,z)) because they are different (array restrictions) and the surf command requires matrices (as x, y or z). • The quiver command works with both the original structure (rx, ry) and this matrix structure. For example so as represent the gradient of the function z=f(x,y) which is the vector field (dz/dx, dz/dy), it can be written (using four matrices): [dx,dy]=gradient(z); quiver(x,y,dx,dy); • For the previous operation, the space so as to calculate the gradient can be choose by adding it for each direction, for example [dx,dy]=gradient(z,0.2,0.2), or [dx,dy]=gradient(z,0.2) in this case.

2. Representation of the contour lines of the function f(x,y) with the contour command writing: contour (x,y,z);

• The z value is constant along each contour line. Then, the contour lines are plane curves for different z values. • A representation in the x-y plane appears in the graphic window. • x, y and z must be matrices again. • The clabel command should be written in order to the z value appears in each contour line: clabel (contour(x,y,z))

Page 13: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 13 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

Using other commands so as to represent scalar fields: ezsurf ezcontour

1. Representation of the function z=cos(xy) between x=-3 and x=3, and between y=-3 and y=3 with the ezsurf command, obtaining the below left figure after writing: ezsurf('cos(x*y) ',[-3 3 -3 3]);

• Remember that a more actual representation is obtained with the command: axis equal • The surf command (z=f(x,y)) needs the discretization (besides a mesh) defined by the user as plot command (y=f(x)) do, and ezsurf (z=f(x,y)) command do not need it as in the case of ezplot command (y=f(x), f(x,y)=0). MATLAB choose the tolerance to have a good view giving to the function the x and y values of selected points so as to generate the surface. • A similar result is obtained with surf command (before left figure) writing: [x,y]=meshgrid(-3:0.05:3,-3:0.05:3); z=cos(x.*y); surf(x,y,z); 2. Representation of the contour lines of the function

2 2-x -yf(x,y)=xe using the ezcontour command writing: ezcontour ('x*exp(-x^2-y^2)') • The contour command needs the discretization defined by the user, and this command does not need that.

-3-2

-10

12

3

-2

0

2

-1

-0.5

0

0.5

1

x

cos(x y)

y

-4-2

02

4

-4-2

02

4-1

-0.5

0

0.5

1

Page 14: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 14 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

7. Scripts and functions Another alternative so as to have a group of commands that always can be used is to generate a script. This is a file (in .m which is a MATLAB format) that can be saved at any time, and that is opened from File>New>Script (File>New>M-File in old versions such us MATLAB 7.0). The script can be executed whenever the user wants writing its name in the command window as any other command. With this procedure, functions not defined by MATLAB or computer programs can be built avoiding that a great number of commands have to be written in the command window when they are needed. The scripts are saved in the folder that the user wants, but this folder must be chosen as current folder so as to they work when the name is written in the command window.

Following this, a program that represents the already used function y=sin(x)-cos2(x) is built. So as to do it, some considerations are made: • The comments that the user wants to do must be done after the symbol: % • The comments will never appear while the program is executed and are only a guideline about the code for the user. • All the MATLAB commands can be used here, writing them as in the command window.

Then, the file is opened and the next lines are written in the new window that appears:

name.m % Graphic of the function x=-5:0.01:5; y=sin(x)-cos(x).^2; plot(x,y,'g','linewidth',2) grid on Then, File>Save is selected in this new window, a name is put, and the file is saved (being stored in the current folder by default). If the file generated was name.m, in the command window it must be put: name

• According to the graphic, the color of curve is green because of the 'g' in the plot command, the thickness of the curve is incremented due to 'linewidth',2 in the plot command, and a grid is drawn due to the grid on command. • This is possible to check that it is the same to put all the commands in the command window.

The generated file can be opened always the user wanted to be modified. To do it, the file must be selected going to File>Open in the main MATLAB window or selected by double click over the file in the current folder window. Following this, a program that calculates the function ln(2) through a series is built. The series is: (-1)k-1/k, k=1,…,n.

This is very usual that the user wants values of certain variables to be given during the execution (this is, without modifying the script before each execution). In this case, this is interesting let the user give the n value so as to see the different results the script gives for different values. This is done easily treating these variables without giving an input value in the script. However, the user must remember which variables were treated in this way so as to give values to these variables in the command window before executing the script. A solution is to use the input command. Its use can be observed in the built program, which is:

Page 15: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 15 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

ln2.m % Calculation of the sum of the first terms of the ln(2) series n=input('Write the number of terms you want: ') k=1:n; % This is wrong to write number^array as this is impossible to elevate a number (or an array % as MATLAB understands a number as an array 1x1) to an array (mxn). Write number.^array % would be an error too according to the restrictions (the dimensions of both arrays are not the % same). However, MATLAB works as if number was the array number*ones(m,n). s=(-1).^(k-1)./k; summation=sum(s) error=abs(summation-log(2))

Now, the script is saved as ln2 for example in the directory C:\ going to File>Save As. Following this, the current folder is changed in the current folder bar (for example), selecting the directory C:\. The current folder will be always indicated in this bar and can be printed in the command window by writing here: pwd

Before executing the file, it should be written the format long command in the command window (if is not activated) so as to see the results in a better way, with more decimal digits. Then, ln2 (the name of the script) is written and the text between quotes will appear in the command window. Following this, the user only writes the number he wants, for example: 1000

• Remember that the functions sum, abs and log (and the format long command) were already defined. • If the input command is not used (avoiding the line in the program), nothing will appear after writing the script name, leading the call to an error (the line and the column of the file in which MATLAB detects the error is printed). In this case, the value of n must be given in the command window before writing the name: n=1000; ln2 • This is a silly function as it is already implemented in MATLAB, and is useful only as an academic example. • Obviously, a better approximation of the ln(2) is obtained as greater is the value of n. For example, for n=103 the error is 4.99 10-4, for n=107 the error is 4.99 10-8 (n must be lower than 108 or overflow is reached).

The variables generated in the script will appear in the workspace once the script is executed. Then, if the same name variables are used in the script and in the workspace before executing, problems could appear. After executing, these variables will be overwritten. On the other hand, wrong values could be used by the script during execution if variables are not initialized here. For example, if the input command is not used and the user does not know that n should be given and fortunately this is in the workspace (will not generate error). A typical case of error is when a few values of an array are given in the script without a previous initialization here (will never generate error as MATLAB creates the variable), and then the complete array is used. MATLAB will use null values for the other coefficients if the variable is not defined in the workspace but will use defined values in other case leading to wrong results. In the next example the variable is well initialized by adding the second statement: Dim=7; B=zeros(dim,1); B(2,3)=4;

Page 16: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 16 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

Another feature is that scripts can be nested. For example, the execution of another script in which ln2 is only written will produces MATLAB executes the ln2.m file. Obviously, both files must be in the same directory. The problem with the scripts is that all the variables will be generated including intermediate variables and usually the user does not require them. For example, in the before example k and s are intermediate variables. The solution is to use functions. They are written in the same type of files (.m) and then a script can be opened too. In fact, only there is this option in old MATLAB version. In new versions, the option File>New>Function (in the main window too) will open a window with the guidelines of the function format. Thus, the files are saved in the same way, and functions can also be nested (or nested with a script). However, a different format is applied. Firstly, the input arguments and the output arguments must be chosen (one of each type is necessary as minimum). For example, in the before case n would be a mandatory input argument. Other arguments could be used but with no sense. As output arguments, it would make sense to choose only summation and error. Again, other variables could be chosen. Then, once the name is chosen, and if only an output argument is chosen, in the first line it must be written: function output_argument = name (input_arguments (between commas))

Following this, the commands are written in the same way as in scripts and in the last line it could be written (this is not mandatory): end

The function has to be saved with the name chosen. Once the file (name.m) is generated, the function is executed by writing in the command window: name (input arguments (between commas))

Below, a function is built so as to sum in the a-row of a matrix A, the vector which is obtained after that a constant k is multiplied by the b-row. As input arguments A, a, b and k are needed, and as output arguments the matrix B, in which the result is saved, is selected.

rows.m function B=rows (A,a,b,k) B=A; B(a,:)=B(a,:)+k*B(b,:); % Another option: % function A=rows (A,a,b,k) % A(a,:)=A(a,:)+k*A(b,:); disp ('end of the program') end At least in the new MATLAB versions, the program allows for making the mistake of putting a wrong name when writing the function. However, what is written in the command window must be exactly the name of the file.

If A is the identity matrix and the constant 4 times the third row is added to the second row it could be writing in the command window: A=eye(4);a=2,b=3,k=4 rows (A,a,b,k)

Thanks to the disp command, the text between quotes appears indicating that the program has been executed. The function prints the results after it.

• An specific name is not necessary, C=eye(4);i=2;j=3;n=4; rows (C,i,j,n) • Numbers can also be put instead of variable names: rows (eye(4),2,3,4)

Page 17: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 17 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

• Coefficients of matrices can also be put: rows ([1 2 3;3 1 3;1 1 0],1,3,-2) • The matrix B is printed though there are semicolons after each line, something that does not happen in the scripts. • The result is saved in ans, B is not in the workspace. So as to copy the function solution to a variable as B for example, it should be written: B= rows (A,a,b,k) • The variables generated in the function are different and they can have the same name. The option commented inside the function would not overwrite A. It would be overwritten only if it is written in the command window: A= rows (A,a,b,k) • If semicolons are not put, which makes sense if B is not an output argument, B would be printed while the execution too. • The disp command only prints the text between quotes without asking for a value as the input command does, this is, without reading from the command window.

When more than one argument is put, it is written in first line: function [output_arguments (between commas or spaces)] = name (input_arguments (between commas))

In this case, this is necessary to use two variables to see the result (or only the first will be printed in ans) writing in the command window: [output arguments (between commas or spaces)]=name (input arguments (between commas))

The next program would do the same as the previous one in a more inefficient way:

rows.m function [Bmod,Borig]=rows (A,a,b,k) Borig=A; [m,n]=size(A); b=A(a,:)+A(b,:)*k; Bmod=[A(1:a-1,:);b;A(a+1:m,:)]; disp ('end of the program') Then, it is written: [A,B]=rows(eye(4),2,3,4)

• Only ans or L with the first variable is generated in the workspace if it is written: rows (eye(4),2,3,4) or L=rows (eye(4),2,3,4) • The maximum of the variables that can be generated in the workspace is the number of output arguments. Intermediate variables as b, m, n does not appear.

In the next example the function is nested so as the make a product over the result of the operation rows(eye(4),2,3,4) writing in the command window for example: c=product(4)

Product.m function Aprod = product(d) [B1,B2]=rows(eye(4),2,3,4); Aprod=B1*d; end Now, it is simple to nest scripts and functions remembering that both must be in the same directory too. Or the file name of a script is written inside the function, or the name of a function is written inside a script taking care of the function structure.

Page 18: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 18 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

8. Loops This is one of the things more useful for the programmers. A loop allows for evaluating an expression dependent of a parameter, giving different values to the parameter between two defined bounds. In MATLAB the loops are generated through two commands, one at the beginning and other at the final, both always necessary. The first command (in the easiest way) where the b1 and b2 are the bounds is: for parameter=b1:b2

Then, the expressions to evaluate are written, and after the last line the loop must be ended with another command, which is: end

Loops can be used as any other command, applying it in functions, scripts or directly in the command window. The operation is not done until the loop is closed with the end command as can be checked in the command window observing that values are not printed before. For this reason, this is the same to put semicolons in the first and last lines commented (as not to put them). If the user does not want to print the results, it is enough to put semicolons in the commands between them.

Below, a script that calculates the fifth potencies of the first ten natural numbers is implemented. With this example, the utility of the command will be shown. Potencies.m for k=1:10 k^5 end % This is the same as: k=1:10; k.^5

• Only the parameter k with dimension (1x1) (besides the variable ans with the same dimension because of the lack of semicolons) is used, taking it the values 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. • The line commented would do the same but storing all the values in the variable k with dimensions (1x10) (besides the variable ans with the same dimension because of the lack of semicolons). Then, this procedure is less efficient according the memory utilization if the stored values will not be necessary after, as in this case. • The steps between the values given to the parameter can be different of the unit doing the same as with arrays. For a step of two units, it would be written: for k=1:2:10 • As when using equally spaced values in arrays, bounds can be negative values (for k=-1:10), and negative steps can be applied (for k=10:-1:-1) taking the loop the values from b1 to b2. • Loops can be nested. For example, the next nested code would do the same as the before: for k=1:2:10, for j=0:1, (j+k)^5,end,end

Following this, it is presented another script in which the sum of the third potencies of the first fifty natural odd numbers is carried out. sum.m summation=0 for k=1:2:100 summation=summation+k^3; end % The result is printed: summation % Less efficient code without the loop: k=1:2:10; k=k.^3; sum(k)

Page 19: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 19 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

9. Conditional statements The conditional statements have at least a condition in their definition. The code written after a condition will be executed only if the condition is verified. They can also be used as any other command, applying it in functions, scripts or directly in the command window. However it makes more sense to apply these statements when programing functions or scripts. Conditions are written through different symbols. Some examples with the meaning are provided below: a==b – a equal to b a~=b – a different to b a<b – a less than b a>b – a greater than a<= – a less than or equal to b a>= – a greater than or equal to b The structure of conditional statements is generated through as many commands as conditions are put plus the final line which always will be necessary and will be (as in the loops): end

One of the more famous conditional statements is the if statement which exists in a lot of programming languages. The easiest way structure of this statement is to put one condition at the beginning, writing: if condition

Then, the code to be verified is written before putting the end command. The execution of the next script shows how the condition is correctly evaluated. Condition.m % Introducción de datos durante la ejecución: i= input('Write a number'); if i>10 disp ('The number is greater than 10') end • As in the case of the loops, semicolons are not necessary after the commands to define the statement. • Another condition can be evaluated only writing after the last commands to be verified the next command (followed by the new commands to be verified): elseif condition • As many conditions as the user wants can be added. • The condition still not evaluated with the before conditions can be evaluated easily writing before the final statement command the next command: else Following this, the program is opened to be completed with more conditions: Condition.m % Introducción de datos durante la ejecución: i= input('Write a number'); if i>10 disp ('The number is greater than 10') elseif i==10 disp ('The number is equal to 10') else disp ('The number is lower than 10') end % Consider that the else command always evaluate all the conditions still not evaluated % if i>10

Page 20: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 20 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

% disp ('The number is greater than 10') % else % disp ('The number is lower than or equal to 10') % end • Remember the use of the symbol == when the if statement is used, instead of the symbol =. • The else command can be omitted still when more than one condition is added. • The if statement can be nested. For example the next statement (in which the last condition has the same meaning as else in this particular case) will produce the same result: if i>10, disp ('The number is greater than 10'), else, if i==10, disp ('The number is equal to 10'), elseif i<10, disp ('The number is lower than 10'), end, end • If the statement is nested, more than one condition must be satisfied at the same time. Another conditional statement, which is in the midway between the loops and the before statement, is the while statement. In fact, this is the same as combining a loop with the if statement. The statement works as a loop during the condition is verified. Obviously, if this is always verified, the loop will not finish leading to MATLAB is always busy to do anything. The solution is to close MATLAB (surely being necessary to end the process through the Ctrl+Alt+Supr Windows instruction) and open it again.

The conditions are written in the same way being necessary to put in the first line before the commands to be verified: while condition

The next script calculates the lower natural number whose factorial is greater than or equal to 104. The factorial is a defined function in MATLAB and is used through the command: factorial () factorial.m % Calculate the lower natural number k in such a way that factorial k! > 104 k=1; while factorial (k)<10000 % The parameter k is a unit greater each time the loop is executed. % Though this is not the interest, the parameter counts the number of executions constituting % the unknown bound b2 (in this particular case) of an original loop. k=k+1; end k % The next code would do the same in a more inefficient way: % Firstly, this is necessary to suppose that the bound b2 will be enough % Here, it is known that k is lower than 10 % for k=1:10 % if factorial (k)>10000 % This is necessary to go out the loop when the condition is satisfied % break % end % end % k • As in the case of the loops, semicolons are not necessary after the commands which define the statement.

Page 21: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 21 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

• The loop does not give different values to the parameter k. The parameter is increased with steps of one unit inside. The equivalence with the original loop is commented at the final of the program considering that the break is a command valid to terminate the loop prematurely both in the loops and in the while statement. • Sometimes this is not necessary to have a parameter both in loops and in the while statement. In the first case, the parameter only will indicate the number of times the code inside is executed. • This statement can be nested too writing a while statement inside another one without forgetting to close both of them (end command). Again, when the statement is nested more than one condition must be satisfied at the same time.

Page 22: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 22 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

10. Input and output files Usually a program (in a file .m) needs data while the execution. So as to avoid writing it inside the program, input text files can be used. In this way different data can be used by the same program without modifying it. Furthermore, this data can be a large amount. For example, a Finite Element Method (FEM) program needs the coordinates of the nodes of the mesh and the connectivities of these nodes which can mean a lot of information if the mesh is refined enough. The input text files to be read by the program are written before, saving the data with MATLAB, with another program, or writing directly the data in the file.

On the other hand, the results of the program can be written in an output text file, for example if the user wants to save it for a future representation. Moreover, representations of the results could be carried out with another program different from MATLAB, being necessary to write the file with a specific format. This is less common as MATLAB allows for good representations.

Following this, they are shown the necessary commands to read the (input) text files and the necessary commands to write generating the (input or output) text files. The text files used here will have the extension: .txt So as to write in a file name.txt the variable: Var

A file is opened denoting the FID that generates a number that identify the file and has internally the pointer that indicates where the file is going to be read. Any name can be given this variable. Firstly, the file is opened for writing being generated if it does not exist (this is the supposed case): FID=fopen('C:\name.txt', 'w');

Note that with 'w' the command can replaces text in the case of the file already exists. If the file is opened for writing since the last line, 'a' should be written. Note that in the command this is indicated a path (where the file is) besides the file name. If only the name is put, MATLAB will save the file in the current folder. Following this, a comment can be introduced directly: fprintf (FID, 'string\n');

Note that the backslash followed by n indicates that the next text printed will be in next line (since the beginning of the line) of the file. Another example is \r which is the carriage return allowing for back to the before line (at the beginning of the line). Both types of symbols modify the pointer of the FID (see other types as \t – horizontal tab, \b – backspace or \f – form feed). Following this, a variable is written with the next command with a format for numbers or characters: fprintf (FID, 'Varformat\n', Var);

Note that Varformat has the format of each number stored in Var. If the variable is a horizontal vector only one format is defined, being necessary to specify as many formats as rows. The command reads in vertical way, reading column by column and printing the information in rows generating in some way a transpose matrix. If the matrix has a dimension of (6x3) and only three formats are defined, the command reads the first three coefficients of the first column and prints it in row format, then reads the three next coefficients of the first column and prints it in row format, and then does the same with the second and third columns. Finally, the matrix is wrong formed. In order to giving the formats, the symbol %s is used for strings (without spaces), %i is used for integers and %f is used for the fixed point notation (see other

Page 23: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 23 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

types as %d – decimal signed notation, %u – decimal unsigned notation or %e – exponential notation). Now, the file is closed writing: fclose(FID);

Note that it is possible to close all the text opened files at the same time writing: fclose('all') So as to read from a file name2.txt the variable Var2:

Firstly, the file is opened to read being necessary that it exists: FID=fopen('C:\name2.txt', 'r');

Note that 'r' indicates that the text is going to be read. Note that in the command this is indicated a path besides the file name. If only the name is put, the file must be in the current folder. Following this, the variable is read: Var2= fscanf(FID, 'Varformat', dimension);

Note that Varfomat was already defined but now will have as many formats as columns are read. Now the final symbol with slash is not put as the command let MATLAB read the entire file at the same time. For this reason the dimension the user wants to read must be put. This is done writing the m and n dimensions of the variable to be read, between brackets. So as define it, this is considered that MATLAB reads in horizontal way from the file and writes the variable in vertical way. Therefore, m is referred to the number of columns in the file (the rows in the variable) and should be equal to the numbers of formats in Varformat. Note that all the columns are read any case and the number of formats has not importance if all of them are the same (if one format is put, MATLAB reads m columns and give the same format to each coefficient).

Then, when the user wants to read the information in a good way, m has to be equal to the number of columns. In other case coefficients of different rows will be read (as many pieces of rows as n indicates, jumping to the next row when necessary) leading to the matrix has not correspondence.

When the user wants to read all the information n has to be equal to the number of files of the file. If the user does not know it, he can write inf as second dimension, and MATLAB will evaluate if the end position of the file (eof) has been reached stopping the process if that occurs. If the user wants a sub-array of an array of the file he should only change the n dimension. Note that if m is not the number of columns and inf is defined, all the coefficients will be read in a bad way.

Note that once a part of the file has been read and the file is not closed, another part of the file can be read using the same command. In this case, the reading will be done since the last position read and if there is not more information MATLAB will return the symbol: []

Note that the way of reading with inf is more slow that if a number is put because it is evaluated if the current line is the final. If the file is big enough it should not be used, being necessary to know the length of the file. Finally the file is closed: fclose(FID); Again, the command window can be used instead of scripts or functions. Following this, some data is writing to generate input text files for a program which uses the Finite Element Method. The mesh considered in the sixth point is used.

Page 24: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 24 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

The coordinates are: P1(1,0), P2(2,1), P3(2,2), P4(1,2), P5(0,1) The connectivities for each triangular element (encircled in the before figure) are the nodes involved, usually taken in anticlockwise direction. Then, a possibly is the order with which the triangles were already defined, and therefore: Element 1 (P1,P2,P5) – E1(1,2,5) Element 2 (P2,P4,P5) – E2(2,4,5) Element 3 (P2,P3,P4) – E3(2,3,4)

See the next example where the files coordinates.txt and connectivities.txt are generated in the current folder. The code writes the coordinates of the nodes of the mesh and the connectivities of the elements of the mesh. Script.m % The next coordinates are considered in an array of dimensions % (2x5)=(number_of_coordinatesxnumber_of_nodes), in such a way that the coordinates % of the first point are in the first column: x=[1,2,2,1,2;0,1,2,2,1]; % The coordinates are saved in a file writing the before data (printed with two decimals % as the 8.2%f is given for each of the two elements of each column): filecoord=fopen('coordinates.txt', 'w'); fprintf(filecoord,' x y\n'); fprintf(filecoord,'----------------------\n'); % The above line do the same as (saving a character variable): % p='----------------------' % fprintf(filecoord,'%s\n',p) fprintf(filecoord, '%8.2f %8.2f\n',x); fclose(filecoord); % The next connectivities are considered in an array of dimensions % (3x3)=(number_of_element_nodesxnumber_of_elements), in such a way that the % nodes related to the first element are in the first column: c=[1,2,2; 2,4,3; 5,5,4]; % The connectivities are actually integer numbers, though it must be remember that % MATLAB treats each number as a double precision number. % The connectivities are saved in another file writing the before data (printed in integer way % as the %8i is given for each of the three elements of each column): fileconnec=fopen('connectivities.txt', 'w'); fprintf(fileconnec, ' P1 P2 P3\n'); fprintf(fileconnec, '---------------------------\n'); fprintf(fileconnec, '%8i %8i %8i\n',c); fclose(fileconnec);

P1

P2

P3 P4

P5 E1

E2 E3

Page 25: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 25 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

The files are generated in the current folder as the user can see (delete them before if they already exists). If the files are open from MATLAB, the next appears:

x y P1 P2 P3 ---------------------- --------------------------- 1.00 0.00 1 2 2 2.00 1.00 2 4 3 2.00 2.00 5 5 4 1.00 2.00 2.00 1.00

Note that if the file is opened with Windows, only one line will appear with the information. A little trick to have a good view is to write in the script \r\n instead of \n. Now, these input files are read with the next script (that could be the first part of the FEM program as indicated): Script.m % The coordinates of the nodes are read from a file. % The text, which has not interest, is printed in the MATLAB variable text, in string way as % the %s is given. The dimension of the variable is 3 as this is the number of strings without % spaces (x, y and ----------------------, that are in two lines). % The coordinates are printed in the MATLAB variable x, in a real number way (by default) % as the expression %f is given. Furthermore, the dimension has to be put between brackets. % As two columns are in the file, the correct dimensions to write the entire array could % be (2x5) which will be the final dimensions the array will have. Another option is to % use (2xinf) that leads to a matrix of 2 rows and so many columns as rows can be % read is stored in x. filecoord=fopen('coordinates.txt', 'r'); text=fscanf(filecoord, '%s',3); x=fscanf(filecoord, '%f %f',[2 inf]); fclose(filecoord); % The connectivities of the element are read from another file. % Again, the text is printed in string way as the %s is given. Now, 4 strings without spaces % (that are in two lines) are read. This text overwrites the text stored in the variable. % The connectivities are printed in the MATLAB variable c, in a real number way (by default) % as the expression %f is given. This is only the way in which the variable is passed (with % more or less decimal digits) as MATLAB treats all the numbers as double % precision numbers. Now, as there are three columns in the file, the dimension chosen % will be (3xinf). fileconnec=fopen('connectivities.txt', 'r'); text=fscanf(fileconnec, '%s',4); c=fscanf(fileconnec, '%f %f %f',[3 inf]); fclose(fileconnec); % This (before code) is the same as putting here the matrices: % x=[1,2,2,1,2;0,1,2,2,1]; c=[1,2,2; 2,4,3; 5,5,4]; % Program FEM: % …

Page 26: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 26 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

Now, x and c, that were generated when the input files were created, are overwritten in the workspace as the user can see (delete them before with clear if the user wants to see that they are generated now).

• After reading the file, x and c are exactly the same as the ones defined previously. Moreover, the dimension of x is the dimension of the original variable (2x5), and the dimension of c is the dimension of the original variable (3x3). Then, it would be same write it directly though the text file is preferable as pointed out in the first part of this point. • Remember that all the arrays read from MATLAB (fprintf) are read in vertical way (transforming to horizontal) and all the arrays read from files (fscanf) are read in horizontal transforming to vertical). • Remember that the line command can be used to represent the mesh. Considering that the column of c indicates the element and the row indicates the node in correspondence with the columns of x=[1,2,2,1,2], y=[0,1,2,2,1], the first element would be: xe1=[x(c(1,1)),x(c(2,1)),x(c(3,1)),x(c(1,1))]; ye1=[y(c(1,1)),y(c(2,1)),y(c(3,1)),y(c(1,1))]; line(xe1,ye1);

It is possible to do it for three elements, but when the mesh is bigger this is no practical. The configuration of the matrix c, will allow for an easy code with the use of loops. Thus, all the mesh is written by doing (i=3 because there are three elements, and for i=1 the before step would be done): for i=1,3, xe=[x(c(1,i)),x(c(2,i)),x(c(3,i)),x(c(1,i))]; ye=[y(c(1,i)),y(c(2,i)),y(c(3,i)),y(c(1,i))]; line(xe,ye); end

In a more abbreviate way, nesting another loop for the nodes involved in each element, it is: for i=1,3,for j=1,3;xe(j)=x(c(j,i)); ye(j)=y(c(j,i)); xe(4)= xe(1); ye(4)=ye(1);line(xe,ye); end;end

• Remember that quiver command can be useful for representing vector fields which usually are results of a 2D FEM program. These results can be printed in an output text file if the user wants. Using other commands: sprint fget ftell fseek

So as to understand how the FID can be useful, an easy example is put. If after opening a file (with the open command) the next command is used, the first line of the file will be printed in the command window: fget(FID)

If the command is written again, the second line of the file will be printed. If the next command is used now, the position in bytes of the pointer is given (one space, digit or character in the file is one byte), this is, the total bytes since the beginning position of the file (bof) to the current position of the file (cof): ftell(FID)

Now, the next command can be used to locate the pointer where the user wants indicating a specific amount of bytes since the current position (in the example 10 bytes): byte=10; fseek(FID,byte, 'cof')

Note that the before command is very useful so as to locate the pointer at the eof or at the bof, only doing: To locate at the eof: fseek(FID,0, 'eof'); To locate at the bof: fseek(FID,0, 'bof');

Page 27: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 27 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

After locating it at the bof, the command fget(FID) would print the same text as before. Note that these commands are very important, because the management of the files applying it will be the faster option when files are large. Using conversion commands: sprint str2num str2double num2str

Sometimes it is useful to print a number as if it was a string, for example when the user wants to print the number with the disp command. That command requires only strings and therefore the number must be converted. Let it be the next variable: Var=5;

The next command (for example in the command window) will produce the conversion easily giving a format by default: k=num2str(Var)

The next command will produce the same besides giving a format to the variable: k=sprint('%4.4f=',Var)

Thus, the next concatenated strings can be written to be printed (useful in programs .m) using the brackets: disp (['The result is: ', num2str(Var)])

Next, two options to do the opposite conversion are shown. The first generates a double precision number (by default) considering the decimal digits of the simple precision, the second generates a double precision number considering the decimal digits of the double precision. Var= str2num(k) Var=str2double(k)

Page 28: Matlab tutorial final (2) - UDCcaminos.udc.es/info/asignaturas/201/Matlab tutorial.pdf · MATLAB tutorial MATLAB is a tool that was originally developed for numeric calculus with

pág 28 de 28

Author: Héctor García Rábade Subject: COMPUTATIONAL FLUID DYNAMICS I Written in: September 2013 Universidade da Coruña Master in Water Engineering

References: Peter J. Acklam (2003). MATLAB array manipulation tips and tricks. http://home.online.no/~pjacklam/matlab/doc/index.html A lot of information about array operations (http://home.online.no/~pjacklam/ is the root page). Xabier Rodríguez Pérez (2006). APUNTES DE MATLAB (http://caminos.udc.es/info/asignaturas/obras_publicas/103/pdfs/matlab) Basic information about MATLAB, in Spanish (some examples of the present tutorial were taken from it)