Boost Fertility New Invention Ups Success Rates.pdf
Ppl for students unit 4 and 5
1. Packages
Let us say you want to use Random class
java.util.Random rand = new java.util.Random()
import java.util.Random;
import java.util.*;
package mypackage;
must appear as first non-comment in the file
naming a library of classes
convention – use all lower case letters
“package” and “import” statements work hand-in-hand
“jar” file
How does compiler finds the classes?
2. Multithreading
What is concurrency?
Browser loading a page – improve throughput
Responsive user interface
Serial execution vs parallel execution
Each independent subtask is called a “thread”
contrast with a process
a quick look under the covers – CPU sharing
Process – self contained running program with its own
address space
Multitasking OS
Thread – single sequential flow of control within a
process
True concurrency – multi processor machine
3. Multithreading
Stepping into an entirely new world
requires paradigm shift
Enables you to create scalable programs
Allows elegant design – like responding to events
How do you create a Thread?
inherit from java.lang.Thread
override run() to define the sub task that you want to be executed
in parallel
Let us see it in action
4. Points to Note
Thread name – constructor
getName()
toString()
start()
can be called from anywhere
unless this is called, thread will never be started
run()
Order of execution
Different output every time we run this code
thread scheduling mechanism is not deterministic
5. Controlling Thread execution
yield()
indicating to the CPU that you have done enough and some
other thread might as well have the CPU
not guaranteed
rarely used
sleep()
cease execution for given number of milliseconds
at least that much
more – depends on when its turn comes next
less – InterruptedException – somebody called interrupt() on this
thread
order is still undeterministic
6. Controlling Thread Execution
join()
one thread may call join() on another thread to wait for the
second thread to complete before proceeding
calling thread is suspended until target thread finishes
Let us see this in action!
Blocking call
Can also be called with a timeout – join(1000)
Call to join() may be aborted by callling interrupt() on the
calling thread – hence a try catch clause is required here as
well
7. Priority
Tells the scheduler how important this thread is
If there are a number of threads blocked and waiting
to be run, the scheduler will lean towards the one
with highest priority first
Is it possible that lower priority threads are never run?
No. Just that they are run less often
setPriority()
JDK has 10 priority levels – but what matters is the
support by OS
Best to use Thread.MAX_PRIORITY,
NORM_PRIORITY and MIN_PRIORITY
8. Daemon Thread
To provide some general service in the background as
long as the program is running but is as such not part of
the essence of the program
When all of the non-daemon threads are complete, the
program is terminated
daemon threads don’t prevent the program from ending
setDaemon(true)
must be called before start()
A non-daemon thread runs main()
isDaemon()
Any thread created by a daemon thread is also by default
daemon
9. Coding Alternatives
What if you already need to inherit from some other
class?
implements Runnable
So you need to have a run() method defined
Create thread by using new Thread(runnable) and
then call start() on the newly created Thread object
getName() is no longer available!
Thread.currentThread().getName()
Let us see this in action!
Task and an object capable of running that task
10. Lifecycle
A thread can be in any one of the four states
New
Thread object created, but haven’t been started yet
cannot run
Runnable
Can be run when the CPU is available for it next
May or may not be running at the moment
Neither dead nor blocked
Dead
normal termination of run() method
Blocked
could be run, but something prevents it from running
scheduler will skip over it and give time to next thread
sleep(), waiting for some I/O to complete, trying to call a synchronized
method on another object and that object’s lock is not available
wait()
11. Issues with concurrency
Two threads trying to use the same shared resource
at the same time
two people trying to park car at the same slot
two people trying to go through a door
See to believe!
12. Solution?
Some way to put a lock when somebody is accessing
a shared resource
Java has built-in support for locks, called monitor
synchronized keyword
method
block
13. Inter-Thread communication
Collision among threads
Cooperation among threads
Handshaking between threads
wait() and notify()
sleep() does not release the lock
wait() releases the lock
execution is suspended, lock is released
You can come out of wait() due to
notify()
notifyAll()
timeout
14. Inter Thread Communication
You can call these methods only from within a
synchronized method or block
Otherwise IllegalMonitorStateException
“busy wait” is not good for CPU
testing a condition in an infinite loop and breaking out when
appropriate
Synchronizing activities between threads
Consumer has to wait for the Producer to produce
Consumer calls wait() after aquiring its lock
Producer calls notify() on that consumer object after
acquiring that guy’s lock
15. Idiom for wait()
while (conditionIsNotMet)
wait();
Java provides one more level of support for inter-
thread communication
Java I/O
PipedWriter
PipedReader
Issue of deadlock
16. Java I/O
Different sources and sinks
console, memory, file, network
Different approach
sequential, random access, buffered, binary, character, by lines, by
words
java < 1.0 only byte oriented library
java > 1.0 also char oriented library
java 1.4 “new” io, performance and functionality
improvements
Java I/O heavily depends upon wrapping or chaining
java.io: about 50 classes, 10 interfaces, 15 exceptions
17. Streams
Streams – for sequential reading/writing
Input vs Output
Character vs Byte
CharacterStreams
ByteStreams
Data Sink vs processing
Memory vs File vs Console vs Network
18. InputStream: different sources
FileInputStream
ByteArrayInputStream
StringBufferInputStream
PipedInputStream
SequenceInputStream
FilterInputStream (base class for
decorator)
DataInputStream (allows to read different types of
primitive data and Strings)
Modifies the way InputStream behaves internally
BufferedInputStream
LineNumberInputStream
PushbackInputStream
21. FileStreams
Open files for reading or writing
Cannot append - use RandomAccessFile instead
String from, to;
…
FileInputStream in = new FileInputStream(from);
FileOutputStream out = new FileOutputStream(to);
copyBytes(in, out);
out.close();
22. FilterStreams
Filter stream classes add features to basic input or
output streams
Chain streams together to combine features
PrintStream FileOutputStream
DataInputStream BufferedInputStream FileInputStream
23. BufferedStreams
By default, most streams are not buffered
Wrap a stream in a BufferedInputStream or
BufferedOutputStream to improve performance
FileInputStream in = new FileInputStream(from);
FileOutputStream out = new FileOutputStream(to);
BufferedInputStream bin =
new BufferedInputStream(in, bufferSize);
BufferedOutputStream bout =
new BufferedOutputStream(out, bufferSize);
copyBytes(bin, bout);
in.close(); bin.close();
out.close(); bout.close();
24. PrintStream
Can print a text representation of any Java type
System.out and System.err are PrintStreams
25. DataStreams
Provide for input and output of java primitive
types(int, float, etc) and Strings
Output format is independent of local machine
architecture(endian-ness)
UTF format provides fir efficient storage of Unicode
strings
DataInput can read in a line as a String
26. Typing a File
private void typeFile(String filename, PrintStream out)
throws IOException {
FileInputStream fin = new FileInputStream(filename);
DataInputStream din = new DataInputStream(fin):
String line;
while ((line = din.readLine()) != null)
out.println(line);
fin.close();
}
27. I/O with Memory
ByteArrayInputStream,
ByteArrayOuputStream - I/O with arrays of bytes
StringBufferInputStream - input from a
String
28. Other Streams
LineNumberInputStream - keeps track of line
numbers
PushbackInputStream - allows pushing back one
character
SequenceInputStream - concatenates two or
more input streams
PipedInputStream, PipedOutputStream - for
communication between threads
29. File
Abstract representation of file and directory path
names
Isn’t used to actually read/write data
It is used to work at a higher level
30. Creating a File
import java.io.*;
class Writer1 {
public static void main(String [] args) {
try { // warning: exceptions possible
boolean newFile = false;
File file = new File // it's only an object
("fileWrite1.txt");
System.out.println(file.exists()); // look for a real file
newFile = file.createNewFile(); // maybe create a file!
System.out.println(newFile); // already there?
System.out.println(file.exists()); // look again
} catch(IOException e) { }
}
}
31. Appending to a File
static void appendStringToFile(String s, String fName)
throws IOException {
RandomAccessFile f =
new RandomAccessFile(fName, “rw”);
f.seek(f.length()); // move to end of file
f.writeBytes(s); //Appends to the end of the file….
f.close();
}
32. Renaming a File
class RenameCommand implements Command {
public int execute (Shell s, String[] args) {
File f1 = new File(args[1]);
File f2 = new File(args[2]);
if(f1.renameTo(f2))
return OK;
else
s.err.println(“rename failed”);
return -1;
}
}
}
33. Readers and Writers
Stream byte oriented
Reader/Writer unicode compliant char oriented
Adapter classes like
InputStreamReader: converts IS to Reader
OutputStreamWriter: converts OutputStream to Writer
36. FileReader
Convenience class for reading character files.
read()
single character
whole stream of characters
fixed number of characters
Usually wrapped by higher level objects like
BufferedReader
improved performance
convenient methods
The constructors of this class assume that the default
character encoding and the default byte-buffer size are
appropriate. To specify these values yourself, construct
an InputStreamReader on a FileInputStream
37. FileWriter
Convenience class for writing character files.
write()
write character(s) or Strings to file
Usually wrapped by high level Writer objects like
BufferedWriter or PrintWriter
The constructors of this class assume that the default
character encoding and the default byte-buffer size
are acceptable. To specify these values yourself,
construct an OutputStreamWriter on a
FileOutputStream
38. Using FileReader and FileWriter
import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File(”Source.txt");
File outputFile = new File(”Target.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();`
out.close();
}
}
39. BufferedReader
To make lower level classes more efficient and easier
to use
use of buffer
readLine()
Read text from a character-input stream, buffering
characters so as to provide for the efficient reading of
characters, arrays, and lines.
The buffer size may be specified, or the default size
may be used. The default is large enough for most
purposes.
40. Note
As of JDK 1.1, the preferred way to read lines of text is
via the BufferedReader.readLine() method.
Programs that use the DataInputStream class to read
lines can be converted to use the BufferedReader
class by replacing code of the form
DataInputStream d =
new DataInputStream(in);
with
BufferedReader d
= new BufferedReader(new
InputStreamReader(in));
41. BufferedReader
Reads the next line of text from this data input
stream. This method successively reads bytes from
the underlying input stream until it reaches the end
of a line of text.
This method blocks until a newline character is read,
a carriage return and the byte following it are read
(to see if it is a newline), the end of the stream is
detected, or an exception is thrown.
42. Another way of accessing BufferedReader
FileReader fr = new FileReader(“inFile”);
BufferedReader br =
new BufferedReader( fr);
………….
fr.close();
br.close();
43. BufferedWriter
Makes lower level classes more efficient and easier to
use
newLine() method
Write text to a character-output stream, buffering
characters so as to provide for the efficient writing of
single characters, arrays, and strings.
The buffer size may be specified, or the default size
may be accepted. The default is large enough for
most purposes.
44. Using BufferedWriter
FileWriter fw = new FileWriter(“outFile”);
BufferedWriter bw =
new BufferedWriter( fw );
…………..
fw.close();
bw.close();
45. PrintWriter
Enhanced significantly in java 5
You can build a PrintWriter with a File or a String
Can use in places where you previously needed a
Writer wrapped with FileWrite and/or
BufferedWriter
New methods make it very flexible and powerful
format()
printf()
append()
46.
47. Write to a File: which classes to use?
Some class that takes File in constructor
Best sounding method
File PrintWriter
File FileWriter PrintWriter println
48. Reading from a file: which classes to use?
File FileReader BufferedReader readLine()
49. Typical Cases
Reading input by lines
File name FileReader BufferedReader readLine()
Reading standard input
System.in InputStreamReader BufferedReader
readLine()
Alternative:
Scanner s = new Scanner(System.in);
s.nextLine()
50. Serializing Objects
How to Write to an ObjectOutputStream
Writing objects to a stream is a straight-forward process. For
example, the following gets the current time in milliseconds by
constructing a Date object and then serializes that object:
FileOutputStream out = new FileOutputStream("theTime");
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject("Today");
s.writeObject(new Date());
s.flush();
Your class must implement Serializable
51. De-serializing objects
How to Read from an ObjectOutputStream
Once you've written objects and primitive data types to a
stream, you'll likely want to read them out again and
reconstruct the objects.
FileInputStream in = new FileInputStream("theTime");
ObjectInputStream s = new ObjectInputStream(in);
String today = (String)s.readObject();
Date date = (Date)s.readObject();
53. HTML
Hyper text Markup Language
Not a programming language
Does not act on external data
Both the data and markup tags are part of the same
document
Mark Up Tags
special instructions for specific display
case in-sensitive
54. Basic Structure
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
Hi, How are you?
</body>
</html
56. More
Hyperlinks
< a href=“index.html> Home Page </a>
Images
<img src=“mailbox.jpg”>
width, height, border attributes
Tables
<table></table>
<tr></tr>
<td></td>
57. CSS
Original intent of HTMl was not to define the format of
the content but to define the content itself
Later tags like font etc. got added
Became a nightmare
Separating design and content
Cascading Style Sheets
Styles define HOW to display HTML elements
Created by Hakon Wium Lie of MIT in 1994
Has become the W3C standard for controlling visual
presentation of web pages
HTML 4.0 onwards – style in a separate CSS file
Separates design elements from structural logic
Lets see it in action!
59. CSS Syntax
A set of rules
Each rule has two main parts
selector
one or more declarations
Comments: /* … */
60. Two Additional Selectors
id
if you want to apply style to a single, unique element
uses the id attribute of the HTML element, and is defined with
a "#“
Lets see it in action
class
to specify style for a group of elements
allows you to set a particular style for many HTML elements
with the same class
uses the HTML class attribute, and is defined with a ".“
Lets see it in action
61. Three Ways to Insert a CSS
External Style Sheet
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
Internal Style Sheet
<head>
<style type="text/css">
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>
Inline Style Sheet
<p style="color:sienna;margin-left:20px">This is a paragraph.</p>
62. “Cascading”
What style will be used when there is more than one
style specified for an HTML element?
all the styles will "cascade" into a new "virtual" style
sheet by the following rules, where number four has
the highest priority
1. Browser default
2. External style sheet
3. Internal style sheet (in the head section)
4. Inline style (inside an HTML element)
64. Advantages of CSS
Faster downloads
Better site maintenance
Reduced bandwidth costs
one style sheet called and cached
Higher search engine rankings
cleaner code
greater density of indexable content
Not all CSS properties may be supported by all
browsers
65. JavaScript
THE scripting language of the web
Used in billions of Web pages to add functionality,
validate forms, communicate with the server, and
much more
Let us first see a demo
66. What is JavaScript
was designed to add interactivity to HTML pages
lightweight programming language
usually embedded directly into HTML pages
interpreted language (means that scripts execute
without preliminary compilation)
implementation of ECMAScript language standard
JavScript has NOTHING TO DO with Java
67. What can JavaScript do?
gives HTML designers a programming tool
can react to events
page finished loading, user clicked on an element
can read and write HTML elements
change content of a HTML element
can be used to validate data
can be used to detect the visitor's browser
and hence show browser specific stuff
can be used to create cookies
68. JavaScript and HTML
HTML <script> tag is used to insert a JavaScript into an
HTML page – either in body or in head
Example of writing HTML
Example of changing HTML
Hiding JavaScript
<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
//-->
</script>
</body>
</html>
69. Functions and Events
JavaScripts in an HTML page will be executed when the
page loads
This is not always what we want
Sometimes we want to execute a JavaScript when
an event occurs, such as when a user clicks a button
When this is the case we can put the script inside
a function
Events are normally used in combination with functions
(like calling a function when an event occurs)
Example!
70. External JavaScript
JavaScript can also be placed in external files
cane be used on several different web pages
File extension .js
External script cannot contain the <script></script>
tags!
To use an external script, point to the .js file in the
"src" attribute of the <script> tag
<script type="text/javascript" src="xxx.js"></script>
Comments: // or /* .. */
71. About JavaScript Syntax
JavaScript is a sequence of statements to be executed
by the browser
Case sensitive
; at the end of each statement is optional
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another
paragraph.</p>");
</script>
statements can be grouped in blocks {}
72. Variables
Variable names are case sensitive (y and Y are two
different variables)
Variable names must begin with a letter, the $ character,
or the underscore character
var x;
var x=5;
var name=“Vishal”;
If you redeclare a JavaScript variable, it will not lose its
value
local (inside and function) and global variables
Assigning Values to Undeclared JavaScript Variables
makes them implicitly global
73. Operators
Arithmetic
+, -, *, /, %, ++, --
Assignment
=, += etc.
+ is also used for concatenation
If you add a number and a string, the result will be a
string!
Comparison Operators
Logical Operators
If .. Else statement
Switch statement
74. GUI
JavaScript has three kind of popup boxes
Alert box
user will have to click “OK” to proceed
alert("sometext");
Confirm box
user will have to click either "OK" or "Cancel" to proceed
If the user clicks "OK", the box returns true. If the user clicks "Cancel",
the box returns false
confirm("sometext");
Prompt box
user will have to click either "OK" or "Cancel" to proceed after entering
an input value
If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null
prompt("sometext","defaultvalue");
75. Functions
A function will be executed by an event or by a call to
the function
to assure that a function is read/loaded by the
browser before it is called, it could be wise to put
functions in the <head> section
function functionname(var1,var2,...,varX)
{
some code
}
76. Loops
for
while
break
continue
var person={fname:"John",lname:"Doe",age:25};
var x;
for (x in person)
{
document.write(person[x] + " ");
}
77. Events
Every element on a web page has certain events
which can trigger a JavaScript
A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input field in an HTML form
Submitting an HTML form
A keystroke
onLoad, onUnload, onSubmit, onMouseOver
78. Objects
JavaScript is Object based programming language
Allows you to define your own objects and make your
own variable types
Object is just a special kind of data. An object has
properties and methods
Objects have attributes and methods.
Many pre-defined objects and object types.
Using objects follows the syntax of C++/Java
objectname.attributename
objectname.methodname()
79. Pre-defined Objects
document
attributes of current document like title, URL, forms, images
etc.
write()
navigator
contains information about the browser
screen
contains info about visitor’s screen
window
represents an open window in the browser
80. Document Object Model
Naming hierarchy used to access individual elements of a
HTML document
<FORM ID=myform ACTION=…
Please Enter Your Age:
<INPUT TYPE=TEXT ID=age NAME=age><BR>
And your weight:
<INPUT TYPE=TEXT ID=weight
NAME=weight><BR>
</FORM>
From javascript you can get at the age input field as:
document.myform.age.value
81. Validation Example
function checkform() {
if (document.myform.age.value == "") {
alert("You need to specify an age");
return(false);
} else {
return(true);
}
}
83. Java Vs JavaScript
• JavaScript • J ava
• Interpreted (not • Compiled on server
compiled) by client. before execution on
• Object-based. Code client.
uses built-in, • Object-oriented.
extensible objects, but Applets cons of object
no classes or classes with
inheritance. inheritance.
• Code integrated with, • Applets distinct from
and embedded in, HTML (accessed from
JAVA
HTML. HTML pages)
83
84. PHP
Powerful tool for making dynamic and interactive web
pages
Counterpart of MS ASP
Server-side scripting language
PHP stands for PHP: Hypertext Preprocessor
PHP scripts are executed on the server
PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
PHP is an open source software
PHP is free to download and use
85. Why is PHP used?
1. Easy to Use
Code is embedded into HTML. The PHP code is enclosed in special start and end tags
that allow you to jump into and out of "PHP mode".
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hi, I'm a PHP script!";
?>
</body>
</html>
86. Why is PHP used?
1. Cross Platform
Runs on almost any Web server on several operating systems.
One of the strongest features is the wide range of supported databases
Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise
Server
Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac
OSX, Windows NT/98/2000/XP/2003
Supported Databases: Adabas D, dBase,Empress, FilePro (read-
only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase,
mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8),
Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm
87. Why is PHP used?
1. Cost Benefits
PHP is free. Open source code means that the entire PHP community will contribute
towards bug fixes. There are several add-on technologies (libraries) for PHP that are
also free.
PHP
Software Free
Platform Free (Linux)
Development Tools Free
PHP Coder, jEdit
88. More about PHP
PHP files can contain text, HTML tags and scripts
PHP files are returned to the browser as plain HTML
PHP files have a file extension of ".php", ".php3", or
".phtml"
PHP runs on different platforms (Windows, Linux, Unix,
etc.)
PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
PHP is FREE to download from the official PHP
resource: www.php.net
PHP is easy to learn and runs efficiently on the server
side
89. How Does It Work?
The PHP script is executed on the server, and the
plain HTML result is sent back to the browser
A PHP script always starts with <?php and ends
with ?>. A PHP script can be placed anywhere in the
document.
<? .. ?>
A PHP file normally contains HTML tags, and some
PHP scripting code.
Each code line in PHP must end with a semicolon
93. Very Good Use
<html><head>
<title>UCR Webmaster Support Group</title>
<link rel="stylesheet" type="text/css"
href=“mycssfile.css">
</head>
<body>
<table width=80% height=30>
<tr><td>
<div align=center> Page Title </div>
</td></tr></table>
94. Very Good Use
<table width=80% height=30>
<tr><td>
<div align=center> UC Riverside
Department<BR>
<a
href=mailto:someuser@ucr.edu>someuser@ucr.
edu</a>
</div>
</td></tr></table>
</body>
</html>
95. Very Good Use
<?php
// header
include(“header.php”);
?>
Insert content here!
<?php
// footer
include(“footer.php”);
?>
96. Additional Resources
• PHP Manual http://docs.php.net/
• PHP Tutorial http://academ.hvcc.edu/~kantopet/php/index.php
• PHP Coder http://www.phpide.de/
• JEdit http://www.jedit.org/
• PHP's creator offers his thoughts on the PHP phenomenon, what has
shaped and motivated the language, and where the PHP movement is
heading
http://www.oracle.com/technology/pub/articles/php_experts/rasmus
_php.html
• Hotscripts – A large number of PHP scripts can be found at:
http://hotscripts.com/PHP/Scripts_and_Programs/index.html
97. MATLAB
MATLAB is a program for doing numerical
computation. It was originally designed for solving
linear algebra type problems using matrices. It’s
name is derived from MATrix LABoratory
Plotting functions ..
Image Processing Basics ..
Robotics Applications ..
GUI Design and Programming
98. MATLAB
The MATLAB environment is command oriented
somewhat like UNIX. A prompt appears on the
screen and a MATLAB statement can be entered.
When the <ENTER> key is pressed, the statement
is executed, and another prompt appears.
If a statement is terminated with a semicolon ( ; ),
no results will be displayed. Otherwise results will
appear before the next prompt
99. MATLAB
MATLAB has since been expanded and now has
built-in functions for solving problems requiring
data analysis, signal processing, optimization, and
several other types of scientific computations. It
also contains functions for 2-D and 3-D graphics
and animation
Everything in MATLAB is a matrix !
101. MATLAB
To get started, type one of these commands: helpwin,
helpdesk, or demo
» a=5;
» b=a/2
b=
2.5000
»
102. Other Features
Variables
Math and Assignment Operators
Relational Operators
Logical Operators
Matrices
first level support for matrix operations
Selection Structures
Repetition Structures
103. MATLAB Matrices
MATLAB treats all variables as matrices. For our purposes
a matrix can be thought of as an array, in fact, that is how
it is stored.
Vectors are special forms of matrices and contain only one
row OR one column.
Scalars are matrices with only one row AND one column
104. MATLAB Matrices
A matrix can be created in MATLAB as follows (note the
commas AND semicolons):
» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
matrix =
1 2 3
4 5 6
7 8 9
105. Use of M-File
There are two kinds of M-files:
Scripts, which do not accept input
arguments or return output arguments. They
operate on data in the workspace.
Functions, which can accept input
arguments and return output arguments.
Internal variables are local to the function.
Click to create
a new M-File
106. M-File as script file
Save file as filename.m
Type what you want to
do, eg. Create matrices
If you include “;” at the
end of each statement,
result will not be shown
immediately
Run the file by typing the filename in the command window
107. Some Useful MATLAB commands
who List known variables
whos List known variables plus their size
help >> help sqrt Help on using sqrt
lookfor >> lookfor sqrt Search for
keyword sqrt in m-files
what >> what a: List MATLAB files in a:
clear Clear all variables from work space
clear x y Clear variables x and y from work space
clc Clear the command window
108. Some Useful MATLAB commands
what List all m-files in current directory
dir List all files in current directory
ls Same as dir
type test Display test.m in command window
delete test Delete test.m
cd a: Change directory to a:
chdir a: Same as cd
pwd Show current directory
which test Display directory path to ‘closest’
test.m
109. MATLAB Toolboxes
109
MATLAB has a number of add-on software modules, called
toolbox , that perform more specialized computations.
Signal Processing
Image Processing
Communications
System Identification
Wavelet Filter Design
Control System
Fuzzy Logic
Robust Control
µ-Analysis and Synthesis
LMI Control
Model Predictive Control
…
110. PROLOG
Logic based language
With a few simple rules, information can be analyzed
.pl files contain lists of clauses
Clauses can be either facts or rules
Predicate, arity 1 (male/1)
Terminates a clause
male(bob).
Argument to predicate
male(harry).
child(bob,harry).
son(X,Y):- Indicates a rule
male(X),child(X,Y).
“and”
111. Rules
Rules combine facts to increase knowledge of the
system
son(X,Y):-
male(X),child(X,Y).
X is a son of Y if X is male and X is a child of Y
112. Questions
Ask the Prolog virtual machine questions
Composed at the ?- prompt
Returns values of bound variables and yes or no
?- son(bob, harry).
yes
?- king(bob, france).
no
113. Questions
Can bind answers to questions to variables
Who is bob the son of? (X=harry)
?- son(bob, X).
Who is male? (X=bob, harry)
?- male(X).
Is bob the son of someone? (yes)
?- son(bob, _).
No variables bound in this case!
114. Backtracking
How are questions resolved?
?- son(X,harry).
Recall the rule:
son(X,Y):-
male(X),child(X,Y).
115. Backtracking
Y is bound to the atom “harry” by the question.
male(X) child(X,Y)
X=harry child(harry,harry)?
Y=harry no
X=bob
Y=harry child(bob,harry)?
yes - succeeds
116. Applications
Intelligent systems
Complicated knowledge databases
Natural language processing
Logic data analysis
Strengths:
Strong ties to formal logic
Many algorithms become trivially simple to implement
Weaknesses:
Complicated syntax
Difficult to understand programs at first sight