Numerical Computing Using By T K Rajan, Govt. Victoria College, Palakkad.

Post on 25-Dec-2015

213 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

Numerical ComputingUsing

ByT K Rajan, Govt. Victoria College, Palakkad

What is SciLab• A programming language with a rich collection of numerical

algorithms

• An Interpreted Language

• Handles various Data Types and user defined ones

• Dynamically compiles and link other languages like FORTRAN, C etc.

• It is a free software with source code

• It focuses on many areas of scientific computing covering algebra, calculus, number theory, signal processing, statistic etc.

• It provides many graphic features like 2D, 3D plotting

• In SciLab everything is a matrix

• It is a case sensitive language

Where to get SciLabScilab binaries can be downloaded directly from the Scilab

homepage

http://www.scilab.orghttp://www.scilab.org/

download

Starting and exiting SciLabDouble Click SciLab Shortcut

scilab-5.2.2

Consortium Scilab (DIGITEO)

Copyright (c) 1989-2010 (INRIA)

Copyright (c) 1989-2007 (ENPC)

________________________________________

Startup execution:

loading initial environment

--> disp "hello"

hello

--> quit (to Exit from SciLab)

Online Help• For online help type help at the command prompt• Another method is type help followed by the name of

function of which help is required• Use apropos command to search a string• exists function name - to check whether a function

exists or not?

-->help -->help sqrt -->exists gcd

-->apropos logarithm – it will search the string ‘logarithm’

<Tab> key provides intellisense.

i.e. press Tab key after typing a letter or a word, a window of associated functions will popup

Editing a command line -->is the scilab command prompt

-->disp “hello Scilab”

• Ctrl+p recall previous line or up arrow key

• Ctrl+b move backward one character

• Ctrl+f move forward one character

• Ctrl+h delete previous character

• Ctrl+d delete one character (at cursor)

• Ctrl+a move to beginning of line• Ctrl+e move to end of line• Ctrl+k delete to the end of the line

Creating variables• No need to declare a variable

• Variables are created when they are set

• The = symbol is used for assigning a value to a variable

-->x=3 ; x=int32(3)

-->y=x*2

-->a=[1 2 3]

-->name=“Rajan”

-->z=complex(2,3)

More about commands• Commands end with semicolon(;) suppress

display

• -->x=12/5;• Commands at the same line (use semicolons

between lines)• -->x =[1 2 3]; y=12/5• A lengthy command (use two or more dots … )• -->x= -23+(12- sin(45))+…

-->5*cos(78)- sqrt(-5+sin(12))

System commands• pwd - to know the current working directory• dir – to know the files in a directory• chdir – to change the working directory• who – to list the variables created in the working directory• Whos – Displays names and specifics of current variables• what – List all primitives and functions• pause – to debug creating a new work space• resume – to return to the original work environment• Clear - Deletes unprotected variables and functions from

memory

• date – displays system date• typeof(a) - Output string with type of variable• whereis - Display name of library containing function

Simple data types

Number Integer, floating-point, complex

String characters in quotes

Boolean T and F

Real number-->x=22

-->y=int(16.23)

-->a=int32(16.23)

Command to change the format of double precision

• -->format(10,’e’) - scientific form

• -->format(10,’v’) – floating arithmetic form

To change the base of a number

• -->dec2hex(49) - other functions … dec2bin dec2oct

• -->hex2dec(‘45AF0’) - other functions … bin2dec oct2dec

Complex Number-->z=sqrt(-3)

-->x=-2+3*%i

-->x=complex(-2,3)

-->a=real(x)

-->b=imag(x)

-->y=conj(x)

Simple data types: operators

• + addition -->x+y• - substraction -->x-y• * multiplication -->x*y• / right division -->x/y• \ left division --> x\y • ^ power --> x^n• ** power (same as ^) --> x**n• ' transpose conjugate --> x’

Arithmetic Statements

• -->a = 3; b = 7.2; c=5• -->c = a + b^2 -

sin(3.1415926/2)• -->(b= -b + sqrt(b^2 – 4* a*

c))/(2*a)

String

A string is in “… “ or ‘ … ‘

Ex:

-->a=“scilab for numerical computation”

-->b=‘mathematics’

String functions:• string() – length() – evstr() or eval() – execstr() –

blanks(n)

• strcat() - + operator – part() – ascii() – isnum()

• strncpy() – gsort() – pol2str() - strrev()

Special Constatnts

%e Euler’s costant

%i Imaginary unit

%pi ∏

%eps 2.220D-16 ( epsilon )

%inf ∞

%t T for True

%f F for False

Relational operators

• < - less than

• > - greater than

• <= - less than or equal to • >= - greater than or equal to

• == - equal to • ~= or <> - not equal to

Logical operators

• & - and operator

• | - or operator

• ~ - not operator

Functions:• islogical() – isnum() – exists – isreal()

Input - Output

• For output use disp() or printf()• Ex:

-->disp(“Enter a Number:”)

-->printf(“Value of n=“)

• For input (read) data use input()• Ex:

-->n=input(“Enter the value of n”)

-->m=input(“”)

Arrays and Matrices

Array: -->a = [1, 2, 3, 4, 5](creates a one dimensional array and stored in a)

Matrix:-->b=[1,2,3;2,3,4;3,4,5] (creates a 3X3 matrix and stored in B)

-->c=[1;2;3](creates a column matrix)

Special Matricesrand(3,5) – creates a random matrix of order 3

x 5

rand(3,5)*100; int32(rand(3,5)*100)

testmatrix(“hilb”,3) – inverse of a Hilbert matrix

testmatrix(“magi”,3) – magic square of size 3

eye(3,3) – creates a 3 x 3 identity matrix

zeros(3,4) – creates a zero matrix of order 3 x 4

ones(3,4) – creates a 3 x 4 matrix of 1’s

Special Matrices – contd..

a=[-3:.01:3] – creates a row matrix (a vector) from -3 to 3 equally spaced of width 0.01

a=linspace(-3,3,100) - creates a row matrix (a vector) of size 100 from -3 to 3

Matrix functions

-->a=[-3, 4, 0;2,-1,-6;5,0,3] - To create a 3 x 3 matrix

a’ - transpose of asum(a,’r’) - column sumssum(a,’c’) – row sums sum(a) – the sum of all entriesprod(a) –product of matrix elements

Matrix Functions continue …roots(B) – roots of a polynomial with

coefficients from the row matrix B

sqrt(A) – element wise square roots

exp(A) – logm(A) – log(A) – log10(a)sin(A) – cos(A) – tan(A) – sec(A)asin(A) – acos(A) – atan(A) – asec(A)round(A) – rounds the entries to the nearest

integers

Matrix Functions continue …diag(a) – diagonal of a[x y]= spec(a) – eigen values and eigen

vectorsinv(a) – inverse of a square matrixdet(C) – determinant of a square the

matrix Ctrace(C) – trace of Crank(A) – Finds rank of a matrixlu(A) - LU factors of Gaussian elimination

Slicing a matrix--> a=int(rand(5,6)*100)

a(2:4,1:3) - submatrix from 2nd row to 4th row and 1st col to 3rd col

a(:,1:3) – submatrix from 1st col to 3rd col

a(3,4) – displays the (3,4)th element of a

a($,$) – displays the last entry of a

matrix(a,3,10) – reshape a to 3 x 10 matrix

x=[-2,3,7]; diag(x) – creates a matrix with diagonal as x

Matrix Operations• A, B matrices

-->A+B

-->A-B

-->3*A – scalar multiplication of A

-->3+A – 3 is added to every entry of A

-->A*B - product of A and B

-->A.*B – element wise multiplication

-->A./B – element wise division

-->A.^n – nth power of entries

Polynomial

-->poly(a, ”x”) – a polynomial in x whose roots are elements of the vector a

-->poly(a, “x”, “coeff”) – a polynomial in x whose coefficients are elements of the vector a

-->x=poly(0,’x’);a=1+2*x+3*x^2Example:

-->a=poly([6,5,1],’x’,’c’) -->b=poly([-1 3],’x’)

Polynomial - functions

if a is a polynomial

-->roots(a) – roots of the polynomial a

-->degree(a) – displays the degree of a-->coeff(a) – displays coefficients of a-->horner(a,2) – value of a at 2-->factors(a) – displays prime factors of a

Polynomial matrixx=poly(0,'x');v=[x*(x+1),x^2*(x+1),(x-2)*(x+1), (3*x^2+2)

… * (x+1)]; - v is a polynomial matrix

pg=hrmt(v) or gcd(v) – pg is the gcd of the polynomials

b=lcm(v) – lcm of polynomials

s=poly(0,'s');H=[s,s*s+2;1-s,1+s]; invr(H) – inverse of a polynomial matrix

b=detr(H) – Determinant of the square polynomial matrix H

tril(H) and triu(H) – lower and upper triangular part of H

Rational function-->a=poly([1 0 3],’x’,’c’); b=poly([2 3 4],’x’)

-->c=a/b - It is rational function (quotient of two polynomials)

-->c.num or numer(c) – The Numerator of c

-->c.den or denom(c) – The Denominator of c

-->[q,r]=pdiv(a, b) – q and r are quotient and remainder when b divides a

-->derivat(c) – derivative of the rational function c

Statistical functions-->a=rand(5,3)*20;

-->sum(a)

-->mean(a)

-->median(a)

-->stdev(a)

-->max(a)

-->min(a)

List

• A list is a collection of data objects• Two types – list() and tlist()Ex:-->A=list(23, [1 2 3], ‘hello’)-->b=tlist(‘a’,[2 3],”erw”)

Linear system of equations• To solve Ax=b where A is m x m matrix and b

is m x 1 matrix

--> linsolve(A,b) or A\b

Scilab Scripts• Script (module) is a program (A set of statements) saved in a

file whose name is with an extension .sci or .sce.• If there are executable statements in the script, then save it

with .sce extension• The command editor() will invoke an editor for typing a script• A script file is executed with the command exec filenameEx:

-->exec sample.sce - To execute sample.sce

-->exec “sample.sce” - To display the content of sample.sce

In the scilab editor click the menu execute or load file options

Control statements (1)

if, if-else, if-elseif-else if a == 0 then disp "zero!" elseif a < 0 then disp "negative!" else disp "positive!“ end

Control statement(2)

Select – caseEx:--> x=3

-->Select x

--> case 1

--> disp x

--> case 3

--> disp (x^2)

--> end

Control statement(3)while() loopwhile(condition), statements, end

Example:

x=1while (x<10) disp(x) x=x+1end

Control statement (4) for loops for starting value : increment : final value ….. end

Example:

s=0 for i=1:2:20 s=s+i end

User defined functions

Function y =f(x) – y is output variable, x is input variable and f is the name of the function

Ex: function y = fact(n) // the function program to find facorial

If n<=1 then y=1 else y=n*fact(n-1) end endfunction

functions contd…..• If more than one value to be returned it is function [x y z] = name(a,b,c)

…..

endfunction

• a, b, c are input variables

• x, y, z are output variables

• The last statement should be endfunction

Function definition – method 2

For the following function

function [x y]=cart(r,t)

x=r*cos(t)

y=r*sin(t)

endfunction

Type

deff('[x y]=cart(r,t)',['x=r*cos(t)';'y=r*sin(t)'])

Function program example//Tn+1(x) = 2xTn(x) –Tn-1(x)-->function ch = cheby(x,n)--> // Compute Chebyshev polynomial of order n for

argument x--> if n == 0--> ch = 1;--> elseif n == 1--> ch = x;--> else--> ch = 2*x*cheby(x,n-1)-cheby(x,n-2);--> end--> endfunction

Functions - Calculus

• --> integrate(‘x^3’,’x’,0,1)• -->derivative(f,2) where f is a user defined

function

• -->derivat(p) where p is a polynomial function

Global Vs Local variables• A global variable is one define in the

SciLab environment, while a local variable is one within a function

• A Local variable is not available in SciLab environment even after the call of the function

Saving and Loading variablesA=[1 2 3;3 4 5; 5 6 7];b=[2;3;4]

To save the values A and b use the command

-->save(‘sam.dat’,A,b) - sam.dat is the file where stored

To load the values of A and b later in Scilab environment use the command

-->load(‘sam.dat’)

Function libraries• Save all .sci files in a folder say “C:\My Scilab”

• --> genlib(‘Mylib’, ‘C:\My Scilab’)

• --> load(‘C:\My Scilab\lib’)

• With these commands all the user defined functions will be loaded into the workspace

Formatted StatementUse printf() command

-->x=22/3; y=x^2

-->printf(“the value of x is %f”,x)

-->printf(“the square of %f is %f”,x,y)• %f and %d are format specification respectively for real,

integer type

• %s is the string format specification

• To display a real number correct to 2 decimal place use %.2f specification

bar Diagram

bar()-->x=[4 12 8 20];-->bar(x,0.5,’r’) – draws bar diagram of bar

width .5 in red color

-->x=[1 2 3]; y=[3 4 -2; 6 3 8]; bar(x,y,’stacked’)

Pie diagram

pie()-->x=[4 12 8 20];-->pie(x,0.5,’r’) – draws bar diagram

of bar width .5 in red color

-->x=[1 2 3]; y=[3 4 -2; 6 3 8];

-->pie(x,y,’stacked’)

Plotting Data

plot2d() and plot()x = [.5 .7 .9 1.3 1.7 1.8 ];y = [.1 .2 .75 1.5 2.1 2.4 ];plot2d(x,y,style=-1)plot(x,y,’r’) - plot in red colorplot(x,y,’o’) – plot with letter ‘o’

Plotting function• 2d plot - plot() – xtitle() – legend()• Ex:

clf() - to clear graphic winow

x=-3*%pi:0.001:3*%pi; plot(x,sin(x))

xtitle(‘title of graph’, ‘x label’, ‘y label’)

legend(“f1”,”f2”)

Plotting a function on an interval

fplot2d()-->function [y]=f(x)

--> y = x*abs(x)/(1+x^2);

-->endfunction

-->x = (-5:0.1:5)';

-->fplot2d(x,f,style=5) or plot(x,f,’r’)

Multiplot - 1• More than one graph can be drawn on the same window

• Example:

• -->t=[-6,.1,6]’;• -->plo2d(t, [t.*sin(t) 1+.5*cos(t)

cos(2*t)]);• -->title(“MultiPlot in the same window”);• -->legend(“tsin t”, “1+.5cos t”, “cos

2t”);

Multiplot - 2• More than one graph can be drawn on the same window

• Use subplot() command

• Example:

-->t=(1:0.1:8)';xset("font",2,3);

-->subplot(2,2,1)

-->plot2d(t,[1.5+0.2*sin(t) 2+cos(t)]);

-->xtitle('Plot2d-Piecewise linear');

-->subplot(2,2,2)

-->plot2d2(t,[1.5+0.2*sin(t) 2+cos(t)]);

-->xtitle('Plot2d2-Piecewise constant');

Multiplot - 3• Graphs can be drawn in separate windows

• Use xset() command

• Example:

• x=[-12,.1,12]’;

• xset(window’,1);plot(x,cos(3*x))•

xset(‘window’,2);plot(x,3*sin(x));

Graph - isoview• To scale both axes use isoview() command

• t=[-4,.4,4]’;• plot(25*sin(t),25*cos(t));• isoview(-1,1,-1,1)

Saving graphic files

• When graph is plotted, it is displayed on a graphic window

• Choosing the menu export to option in file menu of graphic window, it can be saved in picture file format

3d Graphs – graph of a surface

plot3d()-->x=(-3:1/20:3); y=(-4:1/25:4);-->u=x’ *y;-->plot3d(x,y,u);-->plot3d1(x,y,u); colored graph

3d Plot - function

Use fplot3d() - fplot3d1()-->x=[-3:.1:3];y=x;-->deff('[z]=f(x,y)','z = sin(x^2) -

y^4')-->fplot3d(x,y,f)

Thank YouT K Rajan, GVC Palakkad

top related