Ppl for students unit 4 and 5
Upcoming SlideShare
Loading in...5
×
 

Ppl for students unit 4 and 5

on

  • 2,146 views

 

Statistics

Views

Total Views
2,146
Views on SlideShare
2,146
Embed Views
0

Actions

Likes
0
Downloads
17
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Ppl for students unit 4 and 5 Ppl for students unit 4 and 5 Presentation Transcript

  • 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?
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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()
  • 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!
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Overview
  • Copyingprotected void copyBytes(InputStream in, OutputStream out) throws IOException { int b; while (( b = in.read()) != -1) out.write(b); }}
  • 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();
  • FilterStreams Filter stream classes add features to basic input or output streams Chain streams together to combine features PrintStream FileOutputStream DataInputStream BufferedInputStream FileInputStream
  • 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();
  • PrintStream Can print a text representation of any Java type System.out and System.err are PrintStreams
  • 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
  • Typing a Fileprivate 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();}
  • I/O with Memory ByteArrayInputStream, ByteArrayOuputStream - I/O with arrays of bytes StringBufferInputStream - input from a String
  • 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
  • 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
  • Creating a Fileimport java.io.*;class Writer1 { public static void main(String [] args) { try { // warning: exceptions possible boolean newFile = false; File file = new File // its 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) { } }}
  • Appending to a Filestatic 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();}
  • Renaming a Fileclass 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; } }}
  • 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
  • Reader: Overview
  • Writer: Overview
  • 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
  • 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
  • Using FileReader and FileWriterimport 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(); }}
  • 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.
  • 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));
  • 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.
  • Another way of accessing BufferedReader FileReader fr = new FileReader(“inFile”); BufferedReader br = new BufferedReader( fr); …………. fr.close(); br.close();
  • 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.
  • Using BufferedWriter FileWriter fw = new FileWriter(“outFile”); BufferedWriter bw = new BufferedWriter( fw ); ………….. fw.close(); bw.close();
  • 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()
  • Write to a File: which classes to use? Some class that takes File in constructor Best sounding method File  PrintWriter File  FileWriter  PrintWriter  println
  • Reading from a file: which classes to use? File  FileReader  BufferedReader  readLine()
  • 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()
  • 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
  • De-serializing objects How to Read from an ObjectOutputStream  Once youve written objects and primitive data types to a stream, youll 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();
  • Self Study Concurrent issues with thread programming Deadlock
  • 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
  • Basic Structure <html> <head> <title>My First Web Page</title> </head> <body> Hi, How are you? </body> </html
  • Some useful tags <br> <p> <blockquote/> <center/> <!-- ….. --> Heading levels <h1> … <h6> <B>, <I>, <U>, <SMALL>, <BIG> <UL> <LI> <LI> </UL> <OL> <LI> <LI> </OL> <HR>
  • 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>
  • 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!
  • Demo http://www.w3schools.com/css/demo_default.htm
  • CSS Syntax A set of rules Each rule has two main parts  selector  one or more declarations Comments: /* … */
  • 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
  • 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>
  • “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)
  • Useful Properties background  background-color, image, repeat text  color, text-align, text-transform, text-indent font  font-family, font-style, font-size links, lists, tables …
  • 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
  • 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
  • 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
  • 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 visitors browser  and hence show browser specific stuff can be used to create cookies
  • 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>
  • 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!
  • 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 /* .. */
  • 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 {}
  • 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
  • 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
  • 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");
  • 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 }
  • Loops for while break continue var person={fname:"John",lname:"Doe",age:25}; var x; for (x in person) { document.write(person[x] + " "); }
  • 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
  • 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()
  • 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
  • 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
  • Validation Examplefunction checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else { return(true); }}
  • Validation Example<FORM METHOD=GET ACTION=foo.cgi NAME=myform onSubmit="return(checkform())">AGE: <INPUT TYPE=TEXT NAME=Age><INPUT TYPE=SUBMIT></FORM>
  • 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 fromJAVA HTML. HTML pages) 83
  • 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
  • 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, Im a PHP script!"; ?> </body> </html>
  • 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
  • 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
  • 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
  • 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
  • Sample PHP<html><body> <?php echo "Hello World"; ?></body></html>echo or printComments: // or /*…*/
  • Other Features Variables Operators Control Statements Loop Statements Functions
  • Another Example<?php$today_dayofweek = date(“w”);if ($today_dayofweek == 4){ echo “Today is Thursday!”;}else{ echo “Today is not Thursday.”;}?>
  • 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>
  • Very Good Use<table width=80% height=30><tr><td><div align=center> UC RiversideDepartment<BR> <ahref=mailto:someuser@ucr.edu>someuser@ucr.edu</a></div></td></tr></table></body></html>
  • Very Good Use<?php // header include(“header.php”);?>Insert content here!<?php // footer include(“footer.php”);?>
  • 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/• PHPs 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
  • 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
  • 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
  • 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 !
  • The MATLAB User Interface
  • MATLABTo get started, type one of these commands: helpwin, helpdesk, or demo» a=5;» b=a/2b= 2.5000»
  • Other Features Variables Math and Assignment Operators Relational Operators Logical Operators Matrices  first level support for matrix operations Selection Structures Repetition Structures
  • 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
  • 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
  • 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
  • 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 immediatelyRun the file by typing the filename in the command window
  • 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
  • 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
  • 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  …
  • 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 clausemale(bob). Argument to predicatemale(harry).child(bob,harry).son(X,Y):- Indicates a rule male(X),child(X,Y). “and”
  • Rules Rules combine facts to increase knowledge of the systemson(X,Y):- male(X),child(X,Y). X is a son of Y if X is male and X is a child of Y
  • 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
  • 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!
  • Backtracking How are questions resolved??- son(X,harry). Recall the rule:son(X,Y):- male(X),child(X,Y).
  • Backtracking Y is bound to the atom “harry” by the question.male(X) child(X,Y)X=harry child(harry,harry)?Y=harry noX=bobY=harry child(bob,harry)? yes - succeeds
  • Applications Intelligent systems Complicated knowledge databases Natural language processing Logic data analysisStrengths: Strong ties to formal logic Many algorithms become trivially simple to implementWeaknesses: Complicated syntax Difficult to understand programs at first sight
  • Self Study LISP