37
Computational Approach to Materials Science and Engineering Prita Pant and M. P. Gururajan January, 2012 Copyright c 2012, Prita Pant and M P Gururajan. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back- Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”. 1

ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Computational Approach to

Materials Science and Engineering

Prita Pant and M. P. Gururajan

January, 2012

Copyright c© 2012, Prita Pant and M P Gururajan. Permissionis granted to copy, distribute and/or modify this document underthe terms of the GNU Free Documentation License, Version 1.3or any later version published by the Free Software Foundation;with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the sectionentitled “GNU Free Documentation License”.

1

Page 2: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Module: Scilab: the scientific computation

package

Scilab is a high-level interpreted language; it is a free software and is usedprimarily for numerical computations and plotting.

In this chapter, we give a tutorial introduction to working with Scilab.For further information, we recommend the reader to peruse some of thelinks listed in the references below. Note that we also assume that in yourcomputer Scilab is loaded; if not, we recommend that you either visit theScilab homepage or use the Introduction module in Part I of this coursematerial to learn how to load.

1 Working with Scilab

1.1 Invoking Scilab

Open a terminal. Type scilab and Enter. You will get a console as shownin the screenshot, Figure. 1.

1.2 Getting help

Type help in the scilab console and Enter. A help browser pops us as shownin the screenshot, Figure 2.

It is also possible to ask for help on a specific topic: for example, a com-mand like help cos will invoke the help browser with the page which givesinformation on the cosine function call of scilab.

2

Page 3: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 1: The scilab console.

Figure 2: The help browser.

3

Page 4: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

1.3 Modes of working

In this module, we describe two modes of working with Scilab. The first isthe interactive mode; in this mode, we can keep giving commands to scilaband it executes them immediately. On the other hand, it is also possible torun it in the script mode; in this mode, all the commands are written to a fileand the file can then be processed in Scilab using the exec command. Thescilab files with an extension of .sci, contain scilab functions; when invokedwith exec("filename.sci") these functions are loaded. On the other hand,scilab files named with an .sce extension, contain both scilab functions andexecutable commands; when invoked with exec("(filename.sce"), thesefiles are executed.

1.3.1 Plotting sin(x) in interactive mode

Plotting a function in interactive mode is very easy. All you need to do is togive the range of x (as a vector: x = [0:0.1:10], for example means thatthe x value runs from 0 to 10 in steps of 0.1) and then tell scilab to plotx and the corresponding sin(x) value along the x- and y-axis, respectively:plot(x,sin(x)). The plot pops up in its own window. It can be saved byclicking on the File button at the left top and choosing Export to option;this allows you to save the file in the directory of your choice, and, in afigure format and name of your choice. The plot generated is shown in theFigure. 3.

1.3.2 Plotting sin(x) using a script file

If we write all the Scilab commands in a file (say, sinxplot.sce), at theconsole, we can use the File command at the top left corner, click on thebutton Execute and execute the file; or, in the console, type the commandexec("sinxplot.sce") and enter.

Here is the file for plotting sin(x); note that Scilab identifies commentsby the use of the \\ symbol. In data files too, we can use \\ to writeinformation about data for a human reader; Scilab would disregard theselines while plotting.

4

Page 5: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 3: The plot of sin(x).

// The scilab script file for plotting sin(x)

x = [0:0.1:10];

plot(x,sin(x))

The figure generated using the above script is shown in the Figure. 4.

1.4 Plotting more than one curve in the same figure

The following script, for example, plots sin(x) and cos(x) in the samefigure, with lines and points; the sin(x) and cos(x) are plotted in differentcolours. In addition, the script also shows how to do the following:

• Make the plot square;

• Set the x-range (from 0 to 2π, in this case);

• Label the x- and y-axes; and,

• Give a title to the plot.

5

Page 6: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 4: The plot of sin(x) generated using the script sinxplot.sce.

// Scilab script file for plotting sin(x) and cos(x)

//

// Let us set the xrange between 0 and 2 PI; the values increase

// in steps of 0.1

x = [0:0.1:2.*%pi]’;

// Plotting sin and cos

// Note that sin is plotted in green with lines and pluses

// Note that cos is plotted in red with lines and pluses

// The plots are also given titles

// The semi-colon at the end of title is essential

plot(x,[sin(x) cos(x)])

// Let us label the x-axis

xlabel ("Angle")

// Let us label the y-axis

6

Page 7: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

ylabel ("Trigonometric function")

// Let us label the figure

title ("Sin and Cos")

// Let us set the figure to be a square

square (0*%pi,-1,2*%pi,1.0)

// Let us print the generated figure on to a colour eps file

// The figure is titled sincosplot.eps

xs2eps(0,"sincosplot.eps")

The figure generated by GNU Octave is shown in Figure. 5.

1.5 Plotting vectors

It is possible to plot vectors with arrows. This comes handy in plotting vectorfields. In Figure. 6, for example, we show such a vector field plotted usingthe champ command:

// To produce a grid of (x,y) points

x = [1:2:10]’;

y = [1:2:10]’;

X = sin(2*%pi.*x/10);

Y = cos(2*%pi.*y/10);

XX = -X*Y’;

YY = Y*-X’;

// To plot a vector field at the grid points

7

Page 8: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 5: The plot of sin(x) and cos(x) in the same figure.

8

Page 9: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

champ(x,y,XX,YY);

// To save the plot to a file

xs2eps(0,"vectorfield");

Figure 6: The plot of a vector field.

1.6 Plotting data from files

In this section, we show how to plot data stored in a file. Let us con-sider the data files grainsize10KperS.dat, grainsize100KperS.dat andgrainsize1000KperS.dat. They are as given below:

grainsize10KperS.dat

# Grain size data at heating rate of 10 K/s

# The first column is the peak temperature (K)

# The second column is the Mean Volumetric Grain Size (in microns)

9

Page 10: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

# The Third column is the standard deviation

# The fourth column is the number of grains

# The data is from Kumkum Banerjee, Matthias Millitzer,

# Michel Perez, and Xiang Wang, Nonisothermal austenite

# grain growth kinetics in a microalloyed X80 linepipe

# steel, Metallurgical and Materials Transactions A,

# Vol. 41, No. 12, pp. 3161-3172, December 2010.

1223 6.0 0.52 1497

1423 15.0 0.60 670

1623 61.0 0.53 763

grainsize100KperS.dat

# Grain size data at heating rate of 100 K/s

# The first column is the peak temperature (K)

# The second column is the Mean Volumetric Grain Size (in microns)

# The Third column is the standard deviation

# The fourth column is the number of grains

# The data is from Kumkum Banerjee, Matthias Millitzer,

# Michel Perez, and Xiang Wang, Nonisothermal austenite

# grain growth kinetics in a microalloyed X80 linepipe

# steel, Metallurgical and Materials Transactions A,

# Vol. 41, No. 12, pp. 3161-3172, December 2010.

1223 4.4 0.47 1700

1423 11.0 0.54 839

1623 33.0 0.52 514

grainsize1000KperS.dat

# Grain size data at heating rate of 1000 K/s

# The first column is the peak temperature (K)

# The second column is the Mean Volumetric Grain Size (in microns)

# The Third column is the standard deviation

# The fourth column is the number of grains

# The data is from Kumkum Banerjee, Matthias Millitzer,

10

Page 11: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

# Michel Perez, and Xiang Wang, Nonisothermal austenite

# grain growth kinetics in a microalloyed X80 linepipe

# steel, Metallurgical and Materials Transactions A,

# Vol. 41, No. 12, pp. 3161-3172, December 2010.

1223 4.2 0.51 1741

1423 11.0 0.62 596

1623 32.0 0.42 428

It is possible to plot these data in Scilab using the plot command. For exam-ple, the following plot file loads the data file plot "grainsize10KperS.dat"

and plots the data as shown in Figure. 7.

clf;

data = fscanfMat(’grainsize10KperS.dat’);

plot(data(:,1),data(:,2),’+’,’markersize’,10);

xs2eps(0,"Grainsize1");

There are at least three points to note; first is the clf command, whichclears any existing figure and starts with a clean canvas. The second is thecommand for reading data; there are several ways in which data can be read;the spcific method chosen here ignores all the text and loads only the data.Finally, as with GNU Octave, while plotting, we are able to denote the symbolas well as its size.

Unlike gnuplot, and like GNU Octave, in Scilab, a simple plot will plot allthe data in the file.

We can get a plot with labeled axes and appropriate title by executing thefollowing script. We also draw a line through the data points as a guide tothe eye. Note the use of the legend command for putting the key on the plot.The resultant plot is shown in Figure. 8.

clf;

data1 = fscanfMat(’grainsize10KperS.dat’);

plot(data1(:,1),data1(:,2),’+-’);

11

Page 12: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 7: The plot of grain size versus temperature

xlabel ’Temperature (in K)’;

ylabel ’Grain size (in microns)’;

hl = legend([’Heating rate: 10 K/s’]);

xs2eps(0,"Grainsize2");

1.7 Plotting with error bars

Most of the times, the experimental data is typically given along with theerrorbars; the current data is no exception and the error is given as standarddeviation in column 3 of the data files. It is possible to plot the data withthe error bars. Here is a script that would do that. The resultant plot isshown in Figure. 9. Note that the error is given in two parts in the errbar

command: if the data is x and if the error is ±δx, the first value is the −δxand the second error value is the +δx.

clf;

data = fscanfMat(’grainsize10KperS.dat’);

plot2d(data(:,1),data(:,2));

12

Page 13: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 8: The plot of grain size versus temperature, with labeled axes and aline drawn as a guide to the eye.

errbar(data(:,1),data(:,2),data(:,3),data(:,3));

xlabel ’Temperature (in K)’;

ylabel ’Grain size (in microns)’;

hl = legend([’Heating rate: 10 K/s’]);

xs2eps(0,"Grainsize3");

1.8 Plotting specific columns of the data

Suppose we wanted to plot the peak temperature and the number of grains.That is, in the data file, we want to plot the columns 1 and 4. This can bedone using the script shown below. The resultant plot is shown in Figure. 10.

clf;

data = fscanfMat(’grainsize10KperS.dat’);

plot(data(:,1),data(:,4),’+-’);

xlabel ’Temperature (in K)’;

ylabel ’Number of grains’;

13

Page 14: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 9: The plot of grain size versus temperature; the data is plotted witherrobars.

hl = legend([’Heating rate: 10 K/s’]);

xs2eps(0,"NoOfGrains");

1.9 Plotting data from more than one file

Of course, it is possible to plot data from different data files in the same plot.Here is a script that plots data for all the three heating rates. The resultingplot is shown in Figure. 11.

clf;

data1 = fscanfMat(’grainsize10KperS.dat’);

data2 = fscanfMat(’grainsize100KperS.dat’);

data3 = fscanfMat(’grainsize1000KperS.dat’);

plot(data1(:,1),data1(:,2),’+-’);

plot(data2(:,1),data2(:,2),’o-’);

plot(data3(:,1),data3(:,2),’x-’);

xlabel ’Temperature (in K)’;

14

Page 15: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 10: The plot of grain size versus temperature; the data is plotted witherrobars.

ylabel ’Grain size (in microns)’;

hl = legend([’Heating rate: 10 K/s’;’Heating rate: 100 K/s’;

’Heating rate: 1000 K/s’]);

xs2eps(0,"Grainsize4");

1.10 Shifting legends

We see that the legends are on the right hand side and hence are gettingprinted on top of the plot itself in Figure. 11. To avoid that, in the legend

command we can specify the position (2, which means left top), which gen-erates a plot as shown in Figure. 12. The script that generated the figure isalso given below for reference.

clf;

data1 = fscanfMat(’grainsize10KperS.dat’);

data2 = fscanfMat(’grainsize100KperS.dat’);

data3 = fscanfMat(’grainsize1000KperS.dat’);

15

Page 16: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 11: The plot of grain size versus temperature for various heating rates.

plot(data1(:,1),data1(:,2),’+-’);

plot(data2(:,1),data2(:,2),’o-’);

plot(data3(:,1),data3(:,2),’x-’);

xlabel ’Temperature (in K)’;

ylabel ’Grain size (in microns)’;

hl = legend([’Heating rate: 10 K/s’;’Heating rate: 100 K/s’;

’Heating rate: 1000 K/s’],2);

xs2eps(0,"Grainsize5");

1.11 Setting line widths

Let us say we want to make the plots and the axes boxes thicker than thedefault. It can be done using the linewidth command as shown in the scriptbelow. The figure generated using the script is shown in Figure. 13.

// Plotting with thicker axis and thicker line

// Clear the canvas

clf;

16

Page 17: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 12: The plot of grain size versus temperature for various heating rates.The legend is shifted from its default position at right top to left top.

// Set the xrange

x=-10:0.1:10;

// Linewidth determines the thickness of the plot line

plot(x,sin(x),"linewidth",4);

// Get the handle on the axes box

a = gca();

// Set the axes box thickness

a.thickness = 2.;

// Set the axes to be equal

square(-10,-1,10,1);

// Print the plot to a file

xs2eps(0,"ThickFigure")

1.12 Saving figures

As we have been doing in the plots above, using the xs2eps command, theplots can be saved. Here is the plot of tan(x) saved using xs2eps command.

17

Page 18: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 13: The plot of sin(x) with thicker border and thicker lines for theplot.

18

Page 19: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Note that by replacing xs2eps by xs2pdf, xs2jpg, xs2gif, we can generatepdf, jpg and gif files, respectively. A complete listing of available options canbe obtained using help graphics export.

// Plotting with thicker axis and thicker line

// Clear the canvas

clf;

// Set the xrange

x=-10:0.1:10;

// Linewidth determines the thickness of the plot line

plot(x,tan(x),"linewidth",4);

// Get the handle on the axes box

a = gca();

// Set the axes box thickness

a.thickness = 2.;

// Set the axes to be equal

square(-10,-1,10,1);

// Print the plot to a file

xs2eps(0,"tanx")

1.13 3D plots and contours

The following set of commands produce the plot of exp(−(x2 + y2)) shownin Figure 15. Here, in the second and third lines, we are setting the x- andy-range and generate the mesh points using meshgrid in the fourth line. Inthe fifith line, we create the data for each (x,y) pair. The plot3d commandproduces the 3D plot. The default angles of the plot are 30 and 60; we canchange the same by getting the handle on the axes.

clf

x = linspace(-2,2,81)’;

y = linspace(-2,2,81)’;

[X,Y] = meshgrid(x,y);

z = exp(-X.^2-Y.^2);

plot3d(x,y,z);

19

Page 20: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 14: The plot of tan(x).

20

Page 21: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

a = gca();

a.rotation_angles=[84.75 138.25];

xs2eps(0,"Gauss1")

Figure 15: The 3D plot of exp(−(x2 + y2))

It is possible to increase or decrease the density of grid lines. For example,the following script, wherein, in the linspace command, we have replaced81 by 41, produces the Figure. 16, in which the isolines are less dense.

clf

x = linspace(-2,2,41)’;

y = linspace(-2,2,41)’;

[X,Y] = meshgrid(x,y);

z = exp(-X.^2-Y.^2);

plot3d(x,y,z);

21

Page 22: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

a = gca();

a.rotation_angles=[84.75 138.25];

xs2eps(0,"Gauss2")

Figure 16: The 3D plot of exp(−(x2 + y2)) with leaner isolines

We can also make the surface show in colour and as a solid instead of meshedas above. For that we replace the command plot3d with surf. Here is thesource code that generates a colour coded surface (and the resulting figure isshown in Figure. 17).

clf

x = linspace(-2,2,81)’;

y = linspace(-2,2,81)’;

[X,Y] = meshgrid(x,y);

z = exp(-X.^2-Y.^2);

22

Page 23: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

surf(x,y,z);

a = gca();

a.rotation_angles=[54.75 129.75];

xs2eps(0,"Gauss3")

Figure 17: The 3D plot of exp(−(x2 + y2)) with colour coded surface

Finally, it is possible to plot contours below the surface. It is done by exe-cuting the contour command by plot3d. The source code for a plot withcontour is given below. The figure generated by the commands is shown inFigure. 18. Note that we have shifted the plot such that the base where thecontours are shown is visible.

clf

x = linspace(-2,2,81)’;

y = linspace(-2,2,81)’;

23

Page 24: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

[X,Y] = meshgrid(x,y);

z = 0.5+exp(-X.^2-Y.^2);

plot3d(x,y,z);

contour(x,y,z,6);

a = gca();

a.rotation_angles=[84.75 138.25];

a.data_bounds=[-2,-2,0.0;2,2,1.75];

xs2eps(0,"Gauss4")

Figure 18: The 3D plot of exp(−(x2 + y2)) with contours

1.14 Using the GUI instead of the command line

As shown in the (screenshot) Figure. 19, in Scilab, the graphic windowalso has buttons for rotating figures, zooming in and zooming out. Thishelps carry out these actions using the mouse instead giving correspondingcommands at the console. Similarly, as we have had a chance to note earlier,the console and help browser windows also help in carrying out tasks (forexample, executing a given file, or saving an evironment and so on) withouthaving to give commands at the prompt.

24

Page 25: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

Figure 19: Screenshot of the Scilab graphics window.

25

Page 26: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

2 Beyond plotting

In the sections above, we have used Scilab primarily as a plotter. However,plotting is only one of its capabilities. It can be used as a computational tooltoo. For example, you can use Scilab to

• Do matrix algebra;

• Solve systems of linear equations; and,

• Solve ordinary differential equations.

In this subsection, we give an example of each.

2.1 Matrix algebra

Let some second rank material property tensor be described by the followingmatrix (in appropriate units, in some frame of reference):

A =

25 0 00 7 −30 −3 13

We would like to diagonalise this matrix and have a matrix representation forthe tensor in which only diagonal elements are non-zero. As is well known,to diagonalise a matrix, we need to solve the eigenvalue problem. If theeigenvalues are distinct, then, we have to form a matrix S by placing theeigenvectors as columns and carry out a similarity transformation, namely,S−1AS.

Let us consider the first step, namely, finding out the eigenvalues, which isdone using the spec function call as shown below:

-->A = [25,0,0;0,7,-3;0,-3,13]

A =

25. 0. 0.

26

Page 27: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

0. 7. - 3.

0. - 3. 13.

-->D = spec(A)

D =

5.7573593

14.242641

25.

It is also rather straightforward to obtain the eigenvectors and the eigenvaluesby a simple manipulation of the spec command as shown.

-->A = [25,0,0;0,7,-3;0,-3,13]

A =

25. 0. 0.

0. 7. - 3.

0. - 3. 13.

-->[R,D] = spec(A)

D =

5.7573593 0. 0.

0. 14.242641 0.

0. 0. 25.

R =

0. 0. 1.

- 0.9238795 - 0.3826834 0.

- 0.3826834 0.9238795 0.

As noted above, the similarity transformation can now be carried out asshown below:

-->A = [25,0,0;0,7,-3;0,-3,13]

A =

27

Page 28: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

25. 0. 0.

0. 7. - 3.

0. - 3. 13.

-->[R,D] = spec(A)

D =

5.7573593 0. 0.

0. 14.242641 0.

0. 0. 25.

R =

0. 0. 1.

- 0.9238795 - 0.3826834 0.

- 0.3826834 0.9238795 0.

-->inv(R)*A*R

ans =

5.7573593 9.890D-16 0.

2.390D-16 14.242641 0.

0. 0. 25.

Thus, the diagonal matrix which represents out property tensor is:

A =

5.75736 0 00 14.24264 00 0 25

2.2 System of linear equations

The yield stress σy of a polycrystalline material is given by

σy = σi + kd−1

2 (1)

where, σi is the yield strength of a single crystal, k is a constant and d is theaverage grain diameter. This is known as the Hall-Petch relation.

In some material, it is reported that the yield strength increases from about

28

Page 29: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

73 to 481 MPa, when the average grain diameter decreases from 8.4 to 0.056microns. Let us calculate the values of σi and k for this material.

This problem is obviously solved by solving the following system of linearequations:

73 = σi +k√

(8.4×10−6)

481 = σi +k√

(0.056×10−6)

Here is how one can carry out the solution using GNU Octave; note the useof the quote mark ’ next to the vector x which transposes the vector.

-->A = [1,1./sqrt(8.4e-6);1,1./sqrt(56e-9)]

A =

1. 345.03278

1. 4225.7713

-->x = [73,481]

x =

73. 481.

-->y = A\ x’

y =

36.725107

0.1051346

Hence, for this material σi = 36.72511 MPa and k = 0.10513 M N m−3

2 .

2.3 Ordinary differential equation

Consider a metallic sphere, which is removed from a furnace at 1773 K anddropped in water at 323 K. How long does it take to cool to 500 K?

This problem is solved by solving the ordinary differential equation, known

29

Page 30: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

as Newton’s law of cooling, namely,

dT

dt= k(T − 323) (2)

where T is the temperature, t is the time and k is a constant of propor-tionality. Let k be -0.05 in appropriate time units. The initial condition isT (t = 0) = 1773.

This equation can be solved using GNU Octave using the code given below.The plot generated is shown in Figure. 20. From the plot, it is clear that thetemperature of 500 is achieved after about 41 time units.

// Let us define the function, namely dT/dt = -0.05*(T-353)

// Note the necessity of making f a function of both t and T

// even if it is not explicitly dependent on t

function Tdot = f(t,T),Tdot = -0.05*(T-323),endfunction

// Let us give the initial conditions

// Let us also define the time range for which we want the solution

// Note that the first argument is the initial value

// The second argument is the increment

// The third argument is the final value

T0 = 1773.0;t0=0;t = 0:0.1:50;

// Let us use ode to solve the differential equation

T = ode(T0,t0,t,f);

// Let us plot the solution

plot(t,T,"linewidth",4)

// Let us make the plot box thicker and square

30

Page 31: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

a = gca();

a.thickness = 2;

square(0,400,50,1800);

// Let us label the axes

xlabel "Time"

ylabel "Temperature"

// Let us save the plot

xs2eps(0,"cooling")

Figure 20: Temperature as a function of time in a metallic sphere cooledfrom 1773 to 323 K.

31

Page 32: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

3 Exercises

1. Type %e and %pi in scilab prompt. What do you get?

2. How would you plot hyperbolic tangent between -5 and 5?

3. Consider two vectors

A =

325

and

B =

323

Inner and outer mutiply these two vectors. What do you get?

4. Use the plot3d command to plot sin(

x2 + y2))

/√

x2 + y2 between

-10 and 10.

5. Consider the function f(x) = x6 − x4 − 25; plot it to identify thebracket within which the zero lies; once the zero is bracketed, one canuse bisection to identify the root of the polynomial. Write a programto do bisection with the identified bracket and hence find the zero ofthe polynomial.

4 Solutions to the exercises

1. -->%e%e =

2.7182818

-->%pi

%pi =

3.1415927

32

Page 33: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

2. -->x = -5:0.1:5;

-->plot(x,tanh(x))

3. -->a = [3;2;5]

a =

3.

2.

5.

-->b = [3;2;3]

b =

3.

2.

3.

-->a’*b

ans =

28.

-->a*b’

ans =

9. 6. 9.

6. 4. 6.

15. 10. 15.

4. -->x = linspace(-10,10,81)’;

-->y = linspace(-10,10,81)’;

-->[X,Y] = meshgrid(x,y);

-->r = sqrt(X.^2+Y.^2)+1.e-12;

33

Page 34: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

-->z = sin(r)./r;

-->plot3d(x,y,z)

Note the use of . to do element-wise operations on a vector or matrix.We add a very small number, 1.e− 12, so that, in case

(X2 + Y 2) iszero, r equals eps.

The figure generated is shown in Figure. 21.

Figure 21: The ”sombrero” plot: the plot ofsin

(√x2+y2

)

√x2+y2

5. The following set of commands help us plot the function; from the plot,it is clear that the zero lies between 0 and 3.

-->x = linspace(0,5,101)’;

-->f = x.^6-x.^4-25.;

34

Page 35: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

-->plot(x,f)

WARNING: Due to your configuration limitations, Sc

ilab switched in a mode where mixing uicontro

ls and graphics is not available. Type "help

usecanvas" for more information.

-->xgrid

Given the bracket, the following is the program which identifies the rootusing bisection. The solution is found to be 1.8161 as can be readilyverified either by plotting the function between 1.75 and 1.85 or bysubstituting the value in the function itself.

// Definition of the function

function y = f(x), y = x^6-x^4-25, endfunction

// The bracket within which the root lies

a = 0

b = 3

// Tolerance for the calculation

tol = 1.e-4

// The bisection

c = 0.5*(a+b);

// Loop for iteration

while b-c > tol

// Function at the mid-point

y = f(c)

// If the function at midpoint is zero, we have the solution

if y == 0

35

Page 36: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

break;

end

// Otherwise, bracket the zero between the mid-point and one

// of the limits

if f(b)*y < 0

a = c;

else

b = c;

end

// Set the new mid-point

c = 0.5*(a+b)

// Continue

end

5 Self-assessment questions

1. What is the meaning of ’ symbol that follows a vector or a matrix?

2. What is the difference between D = spec(A) and [V,D] = spec(A)?

3. What is the command to print a given plot as a pdf file?

4. Consider a system of linear equations given as the matrix equation, Ax = b. What is the command to solve for x?

5. How do you calculate the square root of a number, say −3?

6. What do the three arguments in the command linspace(-2,2,41)

represent?

36

Page 37: ComputationalApproach to MaterialsScience andEngineering · 1.3.2 Plotting sin(x) using a script file If we write all the Scilab commands in a file (say, sinxplot.sce), at the console,

6 Answers to the self-assessment questions

1. It means the transpose of the vector/matrix.

2. In the case of D = spec(A), the eigenvalues of A are listed as a vec-tor. In the case of [V,D] = spec(A), the eigenvectors are given as thematrix V and the diagonal matrix with the eigenvalues in the diagoalis given by D.

3. xs2pdf(0,"filename")

4. x = A \ b’

5. sqrt(-3)

6. -2 is the starting point; 2 is the end point; the row vector has a totalof 41 points between -2 and 2.

7 References and further reading

• Scilab manual

Available at http://www.scilab.org/publications/

• Spoken Tutorials

Available at http://spoken-tutorial.org/wiki/index.php/Scilab

• Mathematical methods for physics and engineering: a comprehensive

guide, K F Riley, M P Hobson and S J Bence, Cambridge UniversityPress, 2006.

• Materials science and engineering: a first course, V Ragha-van, Fifth edition, PHI Private Ltd, 2008.

• Advanced engineering mathematics, Erwin Kreyzig, 8th edition, Wiley-India, 2010.

• Elementary numerical analysis, Kendall Atkinson, Second edition,John Wiley & Sons, 1994.

37