590 likes | 602 Views
Discover what MATLAB is, a high-level programming language with an intuitive interface integrating computation and graphics. Learn about its features, cost, and how to use MATLAB effectively for various tasks.
E N D
CS005 Introduction to Programming Matlab Eamonn Keogh eamonn@cs.ucr.edu
What is MATLAB? • MATLAB is a programming language. • Others are: C, C++, FORTRAN, Java, Pascal, Basic etc • About one million people know Matlab. • It integrates computation and graphics in one easy to use interface • MATLAB stands for MATrixLABoratory. • MATLAB is very extendable. There are many add-ons (toolboxes) for specific requirements • i.e. aerospace, biology, finance etc
What is MATLAB? • MATLAB is a high-level programming language. • This means (informally) it is closer to English Very low level (machine language) Low level (Assembly language) High level (Matlab language) 01010010101010 01010101010101 10101001010100 101010011111001 …. BCC A7 LDA B2 AND A1 CMP A # HEXERR JMP CTRL …. if customer_age < 21 disp(‘Cannot Drink’) else disp(‘What do you want?’) …
What is MATLAB? • If MATLAB can process and visualize data, why ever use FORTRAN, C, or some other language? • MATLAB is an interpreted language • It is not a compiled language • Therefore identical code executes more slowly, sometimes MUCH more slowly in MATLAB • MATLAB has more memory overhead than equivalent FORTRAN or C programs • MATLAB may be unsafe for some critical systems
What is MATLAB? • Main Features • Simple programming rules • Extended accuracy • Continuity among integer, real and complex values • Comprehensive mathematical library • Extensive graphics tools • Linkages with other languages • Transportability across environment • MATLAB scripts will work on PC, UNIX, Mac
What is MATLAB? • How much does Matlab cost? • If you are a company, about $5,000 • A student can buy it for only $100 • There is a free version, called GNU Octave • We can use matlab for free in the lab • There is also Matlab installed on some library computers
What is MATLAB? • How much of Matlab do we need to know? This CS005 class Matlab But this is a powerful subset
Starting MATLAB • On UNIX: type matlab at command prompt • Click on the MATLAB icon if you are on a PC • Mac can do either… • Issues on startup • MATLAB needs a connection to the license server • Check internet connection • Too many users can use all available licenses • Try again later
Starting MATLAB • Once MATLAB is running the GUI (Graphical User Interface) will appear • Default Window appearance (you can change this)
This is the command prompt >> • Command Window • Main window in MATLAB • Commands entered here
MATLAB displays >> prompt when ready for a command • It may say EDU>> instead (because we are using the academic version) • Will have no >> prompt when processing commands • Newer versions also say “Ready” or “Busy” in lower left corner of GUI
MATLAB GUI • Current Folder Window • Displays contents of the current working directory • MATLAB Search Path • Path that MATLAB uses to search for script and function files • Default path contains all built in MATLAB functions • Can modify path through MATLAB function or going under File>Set Path • MATLAB will ask to modify path if running a program from a folder not in path
MATLAB GUI • Workspace Window • Shows all currently defined variables • Array dimensions • Min, max values • Good debugging tool • Command History • Shows all past commands • Can copy and past commands into command window • Double click will execute command
MATLAB GUI • Other windows include editor window, figure window, variable editor, help, etc • Will discuss editor and figure window in upcoming weeks, get to help window in a little bit
MATLAB GUI • Desktop Menus • File Menu • New • Create new MATLAB program file (m-file) • Open existing m-file • Import data • Set Path • Print files • Open recent m-files
MATLAB GUI • Edit Menu • Copy, cut, paste • Find and replace phrases • Clear command history, workspace • Desktop Menu • Change appearance of desktop • Select windows to display
MATLAB is Case Sensitive • Matlab cares about how you use case • Mistakes can be a huge source of frustration • So Fish FISHfishare three completely different things to Matlab
I have just started matlab… Nothing in my workspace yet Command prompt is ready
Using Matlab as a simple calculator, let us add 5 and 6 Something is in my workspace now Matlab computed the answer to 5 + 6, and called it ‘ans’ Here is my history
Using the semicolon to suppress echoing ; If we use the semicolon is this way, Matlab still adds the numbers, and still puts the answer into ‘ans’, but it does not show the answer show the answer echo the answer display the answer
Using the semicolon to suppress echoing ; We can examine the contents of ansat any time, simply by typing its name.
(arithmetic) Operators • Scalar arithmetic operations Operation MATLAB form • Exponentiation: ^ aba^b • Multiplication: * ab a*b • Right Division: / a / b = a/b a/b • Left Division: \ a \ b = b/a a\b • Addition: + a + b a+b • Subtraction: - a – b a-b • MATLAB will ignore white space between variables and operators
Examples • What is sum of the first 5 natural numbers? • It is just: 1 + 2 + 3 + 4 + 5
Examples • How old was P.G Wodehouse when he died? • He was born in 1881, he died in 1975. • His age at death is: 1975 - 1881
Examples • What is the student to faculty ratio at UCR? • We have 20,746 students, and 1,638 faculty • The ratio is: 20,746/1,638 Note that we do not use formatting commas in Matlab. 1,638 incorrect 1638 correct
Examples • What is the area of the blue square? • We know it is the length of the side, squared. • So it is 11 times 11, or 112 11
Examples • What is the area of the blue square? • We know it is the length of the side, squared. • So it is 11 times 11, or 112 11 So there is more than one way to do this in matlab, this is often the case.
Examples • What is the area of the green square? • We know it is the sum of the area of the two smaller squares (for a right triangle) • So it is: 52 + 112 5 11
Examples • What is Eamonn’s BMI? He is 1.87m tall and 99.79 kg in weight
Examples • What is Eamonn’s BMI, using imperial units? • He is 74 inches tall and 220 lbs in weight It is a little different to the metric version, due to rounding
Example (revisited) (on the need for precedence) • What is the total area of the two squares? • It is 5 * 5 + 11 * 11 • But the order matters…. Left to right… Right to left … Multiplication first… 5 * 5 + 11 * 11 25 + 11 * 11 36 * 11 396 5 * 5 + 11 * 11 5 * 5 + 121 5 * 126 630 5 * 5 + 11 * 11 5 * 5 + 121 25 + 126 151 5 Wrong! Wrong! Right! 11
Precedence: Order of Operations An expression inside parentheses is evaluated on its own before being used by operands outside the parentheses • Parentheses • Exponentiation • Multiplication and division have equal precedence • Addition and subtraction have equal precedence • Evaluation occurs from left to right • When in doubt, use parentheses • MATLAB will help match parentheses for you The acronym PEMDAS is common. It stands for Parentheses, Exponents, Multiplication, Division, Addition, Subtraction.
Area of a Trapezoid 10 What is my area? 8 19 Wrong! = ½(a+b) × h In the wrong example Matlab did… 1/2 * 10 + 19 * 8 5 + 19 * 8 5 + 152 157
Definition • An expression in a programming language is a combination of numbers and operators*, that are interpreted according to the particular rules of precedence for a particular programming language. • 1 + 3 / 4 * 2^8 is a matlab expression • 1 + 3 + is not a matlab expression • -1 is a matlab expression • What time is it is not a matlab expression *Later we will see that it also includes” explicit values, constants, variables, operators, and functions
Introduction to Variables What happens when we calculate 1 + 3 Matlab does the math, and places the answer in the computer memory. The place that is store in is referred to as ‘ans’ Computer memory ans When we calculate 1 + 3 the answer is also echoed to the screen, unless we us a semicolon >> 1 + 3;
What is ‘ans’? • It is a variable • A variable is a symbolic name given to some known or unknown quantity or information. • Every variable has • A name • A value • A type or class (less so, in matlab) ans Computer memory
Every variable has • A name • A value Values can change • A type or class Variables can vary! ans The old value of ‘3’ is gone forever. This is a destructive write ans
When the result of the calculation 5 + 5 is placed in ‘ans’, we say: “ans is assigned the value 10” Or just “ans is assigned 10” ans Computer memory
The value of ‘ans’, stays there forever, until we exit matlab, or we change it. We can get the value of ‘ans’ at anytime simply by typing its name (and hitting <enter>) We can read the value in ans as many times as we want, without changing it This is a nondestructive read ans Computer memory
ans ans ans ans
ans ans ans ans
Matlab puts the result of the last evaluated expression into ans by default. However we can do this more explicitly with the assignment operator, which is ‘=’ We do not say: “ans is equal to 5 plus 6” We say “ans is assigned 5 plus 6” The assignment operator takes the result of the expression on the RHS, an puts it into the variable on the LHS
Creating new Variables In addition to the built in variable ‘ans’, we can create our own variables. We can use these variables just like we used ‘ans’ ans bob sue Computer memory
Let us create some variables and play with them… Pronounce as “hisage is assigned 25”, not as “hisage equals 25”. This is a very important distinction. hisage herage Computer memory
combinedage agedifference hisage herage
Let us calculate the average age of our couple This is wrong! We made a precedence mistake We should have typed >> (hisage + herage )/2 averageage combinedage agedifference hisage herage
Sometimes we have so many variables that we begin to lose track of them. We can always ask Matlab to list the variables using the who command. Doing this reminds me that I have variable called herage. But what is its value? I can just type its name to find out
This example creates or changes the value in agedifference, but it does not change hisage or herage. The only way a variable can change is to be on the left hand side of an assignment operator (Experts: matlab does support a kind of pass by reference) combinedage agedifference hisage herage
A single variable name can appear on both side of an assignment. For example, suppose the lady’s birthday is tomorrow... herage herage