AP3114/Computational Methods for Physicists and Materials Engineers
Dr. Jun FanSep 21, 2015AP3114/Computational Methods for Physicists and Materials Engineers4. Plotting
1Review of Lecture 1Creating a variableComments (//)/continuation(..)Elementary mathematical functionsBoolean (%T, %F)Complex numbersIntegerStrings (test, +)Dynamic variables
2Review of Lecture 2Matrix
Functions to generate matrix (eye, ones, zeros, etc)Empty matrix []Query matrices sizeAccessing elements of matrix A(i,j)a:b:c$: the end of the matrix+,-*,/,\XB=A => X=A/B=AB-1 AX=B => X=A\B=A-1BElementwise operations: .Conjugate transpose:
3
real number/matrix => transpose Complex number/matrix => transpose and conjugatesElementary single quote . only transpose, no conjugating the matrix, be it real or complex.3Review of Lecture 3Looping and branching statementsBranching: if & select/caseLooping: for & whilebreak: exit/interrupt a loopcontinue: to go on to the next loopFunctionsFunction Librarygenlib = compile *.sci files into binary files and store themLoad library Debugging: pause, abort, resume
4Order of commandsSequence: one by one consecutively
Command 1Command 3Command 25Branching: ifSelection/Decision Among Multiple Cases
Condition?True BlockTrue
Commands Commands 6Branching: ifSelection/Decision Among Multiple Cases
Condition?True BlockTrueFalse BlockFalseCommands Commands 7Branching: select/caseMultiple possibilities
Test expressionCase 2Command Case 1Case 4Case 38FlowchartCommand 1Command 3Command 2Condition?True BlockTrueFalse BlockFalseTest expressionCase 2Command Case 1Case 4Case 3ifselectcase9Looping: for or whileRepetition: A means to implement instructions repeatedly
when the starting and ending points are knownWhen the starting and ending points are unknown, but the looping condition is known10forwhileBlock 1Block 2Condition?Block 1Block 2FalseCondition is TrueGiven a number of repetitions11Functions
12Define your own functions
Scilab basic mathematical functions
FunctionsA function can call another function
13Function LibrariesA function library is a collection of functions defined in the Scilab language and stored in a set of filesLike C/C++/Fortran, compile the code, you get a binary file which can executeYou can generate your own Scilab function library similarly
ProcedureCreate *.sci file/scripts containing the function (*.c/*.f90 file)Use genlib to generate binary version of the script (compile)Load the library into Scilab14genlib
Library nameDirectory containing *.sci files
15Load libraryThe startup file is *.scilab or scilab.iniAdd the following lines to this file (or create scilab.ini file), such that our library available at startup
Location: Operation System dependent16
http://gb.weather.gov.hk/wxinfo/pastwx/mws201202c.htm17Outline2D PlotPointsCurvesbarplothistplotcontourLabel: x-axis, y-axis, legend, titleExport
Plot A PointPlot the point A(1:2) with a red pointplot(1,2,.r)
Plot(x,y)19Plot a number of points
Plot(1 D array,`lables`)clf: clear figure 20Plot a linePlot a line AB in blue (by default) going through A(1;2) and B(3;5) plot([1,3],[2,5])
21Plot one curveplot(x,y), where x and y are vectors.
Or clf; 22Plot one curve Consider function f over the interval [-2; 5] by
23Plot two curvesPlot two second curve, in different colors (red and green)
clf: clear figure
24Titles, axes, and legends
25Legend
26Export graphicsor, manually export click File Export to
Type commands: 27bar(x,y)
28Plot two sets of bar
29
Statistics of your classmatesWhich year are you in, 1, 2, or 3?
Do you have any programming experience?
Clear; // clear memoryclc; clf; // clear screen & graphics// year 1 2 and 3 x=[1, 2, 3]; // number of students in year 1/2/3 n1=[2, 11, 10]; // number of students who have programming experience n2=[0 5 8]; bar(x, [n1', n2']) xlabel('Year','fontsize',6) ylabel('No. of students','fontsize',6)title(AP3114 Students Statistics, fontsize,6)
30Histplot: plot a histogram histplot(n, data, ) histplot(x, data, )
Arguments n positive integer (number of classes) x increasing vector defining the classes (x may have at least 2 components) data vector (data to be analyzed)
31histplot
32Rainfall in February 2012 figure (isohyets in millimeters)
http://gb.weather.gov.hk/wxinfo/pastwx/mws201202c.htm33
Contour34function z=my_surface(x, y)z=x*sin(x)^2*cos(y)endfunction
t=linspace(-%pi,%pi,30); contour(t,t,my_surface,10) param3d(x=cos(t), y=sin(t), z=t)
param3d1
plot3d
Plot in 3 dimensions
Summary of Scilab plotting commands
39Uniform distribution
Find its mean value and standard deviation bymean() and stdev()
Normal distributionFind its mean value and standard deviation bymean() and stdev()
Exponential distribution
SimulationSuppose an experiment calls for a coin to be spun 50 times, and the results recorded. Computer simulation is therefore handy as you do not have to repeat such an experiment 50 times.
StatisticsFunctions: mean, median, and st_deviation:
If we apply the functions mean, median, and st_deviation without the r qualifier, the functions provide the statistics of the entire matrix:
M = int(100*rand(20,4))mean(M,'r')median(M,'r')st_deviation(M,'r')mean(M)median(M)st_deviation(M)
44
StatisticsM = Int(100*rand(4,6))mean(M,'c')median(M,'c')st_deviation(M,'c')45Next Week Practical test 1120 mins in class practical test (9:30am-11:30am) Your name will be placed next to a computer based on your SID; Sit next to it.Things you can bring with youPlease bring your student ID card. Open book test, i.e. you can bring refs. books, lecture notes, assignments etc. ( Hard copy only)Things not allowedCell phone or any other electronic devices (not to bring or place it in a bag)No internet is available during the examTo prepare for the exam:(1) Lecture notes (especially things in red or blue boxes)(2) 4 exercises(3) Ref. book: Modeling and Simulation in Scilab/Scicos Chapter 1 & Sections 2.1, 2.2, & 2.4
46HW 447Due: 9am, Oct 5, 2015Late policy: 10% off per day
To be submitted online to Canvas:Save all your codes (*.sci files) into one folder to submit; Do use // to add comments clearly which question you are referring to, when we execute your codes, answers shall be shown on the screen.
Exercise (1)Plot a scatter plot of M(xi,yi) with blue triangles
Save the script file into yourstudentno_lecture4_exe1.sci file, Save your figure and submit it as a plot in your pdf file.
48Exercise (2)Plot y=3*sin(x)/x+cos(x) in the range of x=-4 to 4.Save figures and submit them as a figure in your pdf file; Save your script file into yourstudentno_lecture4_exe2.sci file and submit it.49Exercise (3)Suppose you are holding two balls at the peak of Lion Rock. At time zero, you drop them simultaneously.Ball 1: Free fall,
Ball 2:Air resistance is proportional to the linear power of the velocity
Please do the following to compare two cases:(1) Generate functions to calculate the displacement of ball 1 and ball;(2) Plot the displacement as a function of time on the same plot using two colors, red and blue, respectively(3) Label x-axis Time(s), y-axis Distance(m), add legends to two curves (4) The height of the peak is 495m. Which ball arrives at the horizontal line first and why? Calculate or estimate the time when it arrives at the horizontal line.(5) Save & submit your script file (yourstudentno_lecture4_exe3.sci) and figures.
50Exercise (4)We have plot curves for two functions
(1) Plot them again in the x range of -2 to 5.(2) In what ranges, the first one is larger than the second one (with accuracy 0.01)? (3) Save figures and submit them as a figure in your pdf file; Save your script file into yourstudentno_lecture4_exe4.sci file and submit it.
51Exercise(5)
52Figure 7.15Save figures and submit them as a figure in your pdf file; Save your script file into yourstudentno_lecture4_exe5.sci file and submit it.Exercise (6)Create the following plot53
Save figures and submit them as a figure in your pdf file; Save your script file into yourstudentno_lecture4_exe6.sci file and submit it.Exercise(7)
sin(x) cosh (y)(a)(b)Create ausing plot3d.Exercise(8)A drunk man was returning to his house from the bar. The house is very near the bar just 10 steps away. But he was so drunk that he only had 60% chance for each step of heading towards home. Simulate the situation and calculate whether he could arrive home in 600 steps.Exercise(9)Suppose a certain type of bacteria divides into two in a given time interval with a probability of 0.8, and that if it does not dived, it dies. Simulate that with a start of 4 bacteria, how many bacteria is left after two times of division.Exercise(10)In a game of Bingo the numbers 1-99 are drawn at random from a bag. Write a script to simulate the draw of numbers (each number can be drawn only once). Store the sequence of drawing into a vector.Exercise(11)Dribblefire Jets Inc. make two types of aeroplane, the two-engined DFII, and the four-engined DFIV. The engines are terrible and fail with probability 0.5 on a standard flight (the engines fail independently of each other). The manufacturers claim that the planes can fly if at least half of their enignes are working, i.e. the DFII will crash only if both its engines fail, while the DFIV will crash if all four, or if any three engines fail. You worked for the Civil Aviation Board to ascertain which of the two models is less likely to crash. Since parachutes are expensive, the cheapest (and safest) way to do this is to simulate a large number of flights of each model. For example, two calls of random number generator could represent one standard DFII flight: If both random numbers are less than 0.5, that flight crashes, otherwise it doesnt. Write a script which simulates a large number of (at least 500) flights of both models, and estimates the probability of a crash in each case.