SlideShare a Scribd company logo
6.094
Introduction to Programming in MATLAB
Danilo Šćepanović
IAP 2010
Lecture 1: Variables, Scripts,
and Operations
Course Layout
• Lectures
1: Variables, Scripts and Operations
2: Visualization and Programming
3: Solving Equations, Fitting
4: Images, Animations, Advanced Methods
5: Optional: Symbolic Math, Simulink
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Command Window
Current directory
Workspace
Command History
Courtesy of The MathWorks, Inc. Used with permission.
Making Folders
• Use folders to keep your programs organized
• To make a new folder, click the ‘Browse’ button next to ‘Current
Directory’
• Click the ‘Make New Folder’ button, and change the name of the
folder. Do NOT use spaces in folder names. In the MATLAB
folder, make two new folders: IAPMATLABday1
• Highlight the folder you just made and click ‘OK’
• The current directory is now the folder you just created
• To see programs outside the current directory, they should be in
the Path. Use File-> Set Path to add folders to the path
Customization
• File Preferences
Allows you personalize your MATLAB experience
Courtesy of The MathWorks, Inc. Used with permission.
MATLAB Basics
• MATLAB can be thought of as a super-powerful
graphing calculator
Remember the TI-83 from calculus?
With many more buttons (built-in functions)
• In addition it is a programming language
MATLAB is an interpreted language, like Java
Commands executed line by line
Help/Docs
• help
The most important function for learning MATLAB on
your own
• To get info on how to use a function:
» help sin
Help lists related functions at the bottom and links to
the doc
• To get a nicer version of help with examples and easy-to-
read descriptions:
» doc sin
• To search for a function by specifying keywords:
» doc + Search tab
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Scripts: Overview
• Scripts are
collection of commands executed in sequence
written in the MATLAB editor
saved as MATLAB files (.m extension)
• To create an MATLAB file from command-line
» edit helloWorld.m
• or click
Courtesy of The MathWorks, Inc. Used with permission.
Scripts: the Editor
* Means that it's not saved
Line numbers
Comments
MATLAB file
path
Help file
Possible breakpoints
Debugging tools
Real-time
error check
Courtesy of The MathWorks, Inc. Used with permission.
Scripts: Some Notes
• COMMENT!
Anything following a % is seen as a comment
The first contiguous comment becomes the script's help file
Comment thoroughly to avoid wasting time later
• Note that scripts are somewhat static, since there is no
input and no explicit output
• All variables created and modified in a script exist in the
workspace even after it has stopped running
Exercise: Scripts
Make a helloWorld script
• When run, the script should display the following text:
• Hint: use disp to display strings. Strings are written
between single quotes, like 'This is a string'
Hello World!
I am going to learn MATLAB!
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Variable Types
• MATLAB is a weakly typed language
No need to initialize variables!
• MATLAB supports various types, the most often used are
» 3.84
64-bit double (default)
» ‘a’
16-bit char
• Most variables you’ll deal with will be vectors or matrices of
doubles or chars
• Other types are also supported: complex, symbolic, 16-bit
and 8 bit integers, etc. You will be exposed to all these
types through the homework
Naming variables
• To create a variable, simply assign a value to a name:
» var1=3.14
» myString=‘hello world’
• Variable names
first character must be a LETTER
after that, any combination of letters, numbers and _
CASE SENSITIVE! (var1 is different from Var1)
• Built-in variables. Don’t use these names!
i and j can be used to indicate complex numbers
pi has the value 3.1415926…
ans stores the last unassigned value (like on a calculator)
Inf and -Inf are positive and negative infinity
NaN represents ‘Not a Number’
Scalars
• A variable can be given a value explicitly
» a = 10
shows up in workspace!
• Or as a function of explicit values and existing variables
» c = 1.3*45-2*a
• To suppress output, end the line with a semicolon
» cooldude = 13/3;
Arrays
• Like other programming languages, arrays are an
important part of MATLAB
• Two types of arrays
(1) matrix of numbers (either double or complex)
(2) cell array of objects (more advanced data structure)
MATLAB makes vectors easy!
That’s its power!
Row Vectors
• Row vector: comma or space separated values between
brackets
» row = [1 2 5.4 -6.6]
» row = [1, 2, 5.4, -6.6];
• Command window:
• Workspace:
Courtesy of The MathWorks, Inc. Used with permission.
Column Vectors
• Column vector: semicolon separated values between
brackets
» column = [4;2;7;4]
• Command window:
• Workspace:
Courtesy of The MathWorks, Inc. Used with permission.
size & length
• You can tell the difference between a row and a column
vector by:
Looking in the workspace
Displaying the variable in the command window
Using the size function
• To get a vector's length, use the length function
Matrices
• Make matrices like vectors
• Element by element
» a= [1 2;3 4];
• By concatenating vectors or matrices (dimension matters)
» a = [1 2];
» b = [3 4];
» c = [5;6];
» d = [a;b];
» e = [d c];
» f = [[e e];[a b a]];
» str = ['Hello, I am ' 'John'];
Strings are character vectors
1 2
3 4
a
⎡ ⎤
= ⎢ ⎥
⎣ ⎦
save/clear/load
• Use save to save variables to a file
» save myFile a b
saves variables a and b to the file myfile.mat
myfile.mat file is saved in the current directory
Default working directory is
» MATLAB
Make sure you’re in the desired folder when saving files. Right
now, we should be in:
» MATLABIAPMATLABday1
• Use clear to remove variables from environment
» clear a b
look at workspace, the variables a and b are gone
• Use load to load variable bindings into the environment
» load myFile
look at workspace, the variables a and b are back
• Can do the same for entire environment
» save myenv; clear all; load myenv;
Exercise: Variables
Get and save the current date and time
• Create a variable start using the function clock
• What is the size of start? Is it a row or column?
• What does start contain? See help clock
• Convert the vector start to a string. Use the function
datestr and name the new variable startString
• Save start and startString into a mat file named
startTime
Exercise: Variables
Read in and display the current date and time
• In helloWorld.m, read in the variables you just saved using
load
• Display the following text:
• Hint: use the disp command again, and remember that
strings are just vectors of characters so you can join two
strings by making a row vector with the two strings as sub-
vectors.
I started learning MATLAB on *start date and time*
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Basic Scalar Operations
• Arithmetic operations (+,-,*,/)
» 7/45
» (1+i)*(2+i)
» 1 / 0
» 0 / 0
• Exponentiation (^)
» 4^2
» (3+4*j)^2
• Complicated expressions, use parentheses
» ((2+3)*3)^0.1
• Multiplication is NOT implicit given parentheses
» 3(1+0.7) gives an error
• To clear command window
» clc
Built-in Functions
• MATLAB has an enormous library of built-in functions
• Call using parentheses – passing parameter to function
» sqrt(2)
» log(2), log10(0.23)
» cos(1.2), atan(-.8)
» exp(2+4*i)
» round(1.4), floor(3.3), ceil(4.23)
» angle(i); abs(1+i);
Exercise: Scalars
You will learn MATLAB at an exponential rate! Add the
following to your helloWorld script:
• Your learning time constant is 1.5 days. Calculate the number of
seconds in 1.5 days and name this variable tau
• This class lasts 5 days. Calculate the number of seconds in 5 days
and name this variable endOfClass
• This equation describes your knowledge as a function of time t:
• How well will you know MATLAB at endOfClass? Name this
variable knowledgeAtEnd. (use exp)
• Using the value of knowledgeAtEnd, display the phrase:
• Hint: to convert a number to a string, use num2str
/
1 t
k e τ−
= −
At the end of 5 days, I will know X% of MATLAB
Transpose
• The transpose operators turns a column vector into a row
vector and vice versa
» a = [1 2 3 4+i]
» transpose(a)
» a'
» a.'
• The ' gives the Hermitian-transpose, i.e. transposes and
conjugates all complex numbers
• For vectors of real numbers .' and ' give same result
Addition and Subtraction
• Addition and subtraction are element-wise; sizes must
match (unless one is a scalar):
• The following would give an error
» c = row + column
• Use the transpose to make sizes compatible
» c = row’ + column
» c = row + column’
• Can sum up or multiply elements of vector
» s=sum(row);
» p=prod(row);
[ ]
[ ]
[ ]
12 3 32 11
2 11 30 32
14 14 2 21
−
+ −
=
12 3 9
1 1 2
10 13 23
0 33 33
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
⎢ ⎥ ⎢ ⎥ ⎢ ⎥−⎢ ⎥ ⎢ ⎥ ⎢ ⎥− =
⎢ ⎥ ⎢ ⎥ ⎢ ⎥− −
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
−⎣ ⎦ ⎣ ⎦ ⎣ ⎦
Element-Wise Functions
• All the functions that work on scalars also work on vectors
» t = [1 2 3];
» f = exp(t);
is the same as
» f = [exp(1) exp(2) exp(3)];
• If in doubt, check a function’s help file to see if it handles
vectors elementwise
• Operators (* / ^) have two modes of operation
element-wise
standard
Operators: element-wise
• To do element-wise operations, use the dot: . (.*, ./, .^).
BOTH dimensions must match (unless one is scalar)!
» a=[1 2 3];b=[4;2;1];
» a.*b, a./b, a.^b all errors
» a.*b', a./b’, a.^(b’) all valid
[ ]
4
1 2 3 2
1
1 4 4
2 2 4
3 1 3
3 1 3 1 3 1
.* ERROR
.*
.*
⎡ ⎤
⎢ ⎥ =⎢ ⎥
⎢ ⎥⎣ ⎦
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
⎢ ⎥ ⎢ ⎥ ⎢ ⎥=⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎣ ⎦ ⎣ ⎦ ⎣ ⎦
× × = ×
1 1 1 1 2 3 1 2 3
2 2 2 1 2 3 2 4 6
3 3 3 1 2 3 3 6 9
3 3 3 3 3 3
.*
.*
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
⎢ ⎥ ⎢ ⎥ ⎢ ⎥=⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎣ ⎦ ⎣ ⎦ ⎣ ⎦
× × = ×
2 2
2 2
1 2 1 2
2
3 4 3 4
.^
Can be any dimension
⎡ ⎤⎡ ⎤
= ⎢ ⎥⎢ ⎥
⎣ ⎦ ⎣ ⎦
Operators: standard
• Multiplication can be done in a standard way or element-wise
• Standard multiplication (*) is either a dot-product or an outer-
product
Remember from linear algebra: inner dimensions must MATCH!!
• Standard exponentiation (^) can only be done on square matrices
or scalars
• Left and right division (/ ) is same as multiplying by inverse
Our recommendation: just multiply by inverse (more on this
later)
[ ]
4
1 2 3 2 11
1
1 3 3 1 1 1
*
*
⎡ ⎤
⎢ ⎥ =⎢ ⎥
⎢ ⎥⎣ ⎦
× × = ×
1 1 1 1 2 3 3 6 9
2 2 2 1 2 3 6 12 18
3 3 3 1 2 3 9 18 27
3 3 3 3 3 3
*
*
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
⎢ ⎥ ⎢ ⎥ ⎢ ⎥=⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎣ ⎦ ⎣ ⎦ ⎣ ⎦
× × = ×
1 2 1 2 1 2
2
3 4 3 4 3 4
^ *
Must be square to do powers
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
=⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎣ ⎦ ⎣ ⎦ ⎣ ⎦
Exercise: Vector Operations
Calculate how many seconds elapsed since the start of
class
• In helloWorld.m, make variables called secPerMin,
secPerHour, secPerDay, secPerMonth (assume 30.5 days
per month), and secPerYear (12 months in year), which
have the number of seconds in each time period.
• Assemble a row vector called secondConversion that has
elements in this order: secPerYear, secPerMonth,
secPerDay, secPerHour, secPerMinute, 1.
• Make a currentTime vector by using clock
• Compute elapsedTime by subtracting currentTime from
start
• Compute t (the elapsed time in seconds) by taking the dot
product of secondConversion and elapsedTime (transpose
one of them to get the dimensions right)
Exercise: Vector Operations
Display the current state of your knowledge
• Calculate currentKnowledge using the same relationship as
before, and the t we just calculated:
• Display the following text:
/
1 t
k e τ−
= −
At this time, I know X% of MATLAB
Automatic Initialization
• Initialize a vector of ones, zeros, or random numbers
» o=ones(1,10)
row vector with 10 elements, all 1
» z=zeros(23,1)
column vector with 23 elements, all 0
» r=rand(1,45)
row vector with 45 elements (uniform [0,1])
» n=nan(1,69)
row vector of NaNs (useful for representing uninitialized
variables)
The general function call is:
var=zeros(M,N);
Number of rows Number of columns
Automatic Initialization
• To initialize a linear vector of values use linspace
» a=linspace(0,10,5)
starts at 0, ends at 10 (inclusive), 5 values
• Can also use colon operator (:)
» b=0:2:10
starts at 0, increments by 2, and ends at or before 10
increment can be decimal or negative
» c=1:5
if increment isn’t specified, default is 1
• To initialize logarithmically spaced values use logspace
similar to linspace, but see help
Exercise: Vector Functions
Calculate your learning trajectory
• In helloWorld.m, make a linear time vector tVec that has
10,000 samples between 0 and endOfClass
• Calculate the value of your knowledge (call it
knowledgeVec) at each of these time points using the same
equation as before:
/
1 t
k e τ−
= −
Vector Indexing
• MATLAB indexing starts with 1, not 0
We will not respond to any emails where this is the
problem.
• a(n) returns the nth element
• The index argument can be a vector. In this case, each
element is looked up individually, and returned as a vector
of the same size as the index vector.
» x=[12 13 5 8];
» a=x(2:3); a=[13 5];
» b=x(1:end-1); b=[12 13 5];
[ ]13 5 9 10a =
a(1) a(2) a(3) a(4)
Matrix Indexing
• Matrices can be indexed in two ways
using subscripts (row and column)
using linear indices (as if matrix is a vector)
• Matrix indexing: subscripts or linear indices
• Picking submatrices
» A = rand(5) % shorthand for 5x5 matrix
» A(1:3,1:2) % specify contiguous submatrix
» A([1 5 3], [1 4]) % specify rows and columns
14 33
9 8
⎡ ⎤
⎢ ⎥
⎣ ⎦
b(1)
b(2)
b(3)
b(4)
14 33
9 8
⎡ ⎤
⎢ ⎥
⎣ ⎦
b(1,1)
b(2,1)
b(1,2)
b(2,2)
Advanced Indexing 1
• To select rows or columns of a matrix, use the :
» d=c(1,:); d=[12 5];
» e=c(:,2); e=[5;13];
» c(2,:)=[3 6]; %replaces second row of c
12 5
2 13
c
⎡ ⎤
= ⎢ ⎥−⎣ ⎦
Advanced Indexing 2
• MATLAB contains functions to help you find desired values
within a vector or matrix
» vec = [5 3 1 9 7]
• To get the minimum value and its index:
» [minVal,minInd] = min(vec);
max works the same way
• To find any the indices of specific values or ranges
» ind = find(vec == 9);
» ind = find(vec > 2 & vec < 6);
find expressions can be very complex, more on this later
• To convert between subscripts and indices, use ind2sub,
and sub2ind. Look up help to see how to use them.
Exercise: Indexing
When will you know 50% of MATLAB?
• First, find the index where knowledgeVec is closest to 0.5.
Mathematically, what you want is the index where the value
of is at a minimum (use abs and min).
• Next, use that index to look up the corresponding time in
tVec and name this time halfTime.
• Finally, display the string:
Convert halfTime to days by using secPerDay
0.5knowledgeVec −
I will know half of MATLAB after X days
Outline
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Did everyone sign in?
Plotting
• Example
» x=linspace(0,4*pi,10);
» y=sin(x);
• Plot values against their index
» plot(y);
• Usually we want to plot y versus x
» plot(x,y);
MATLAB makes visualizing data
fun and easy!
What does plot do?
• plot generates dots at each (x,y) pair and then connects the dots
with a line
• To make plot of a function look smoother, evaluate at more points
» x=linspace(0,4*pi,1000);
» plot(x,sin(x));
• x and y vectors must be same size or else you’ll get an error
» plot([1 2], [1 2 3])
error!!
10 x values:
0 2 4 6 8 10 12 14
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
0 2 4 6 8 10 12 14
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
1000 x values:
Exercise: Plotting
Plot the learning trajectory
• In helloWorld.m, open a new figure (use figure)
• Plot the knowledge trajectory using tVec and
knowledgeVec. When plotting, convert tVec to days by
using secPerDay
• Zoom in on the plot to verify that halfTime was calculated
correctly
End of Lecture 1
(1) Getting Started
(2) Scripts
(3) Making Variables
(4) Manipulating Variables
(5) Basic Plotting
Hope that wasn’t too much!!
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLAB®
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
Ad

More Related Content

What's hot (20)

Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Lecture 19 matlab_script&function_files06
Lecture 19 matlab_script&function_files06Lecture 19 matlab_script&function_files06
Lecture 19 matlab_script&function_files06
Aman kazmi
 
Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template Library
Anirudh Raja
 
Introduction data structure
Introduction data structureIntroduction data structure
Introduction data structure
MUHAMMAD ISMAIL
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Martin Toshev
 
Java8
Java8Java8
Java8
Felipe Mamud
 
Cupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmCupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithm
TarikuDabala1
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
langer4711
 
Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
icarter09
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
Lists
ListsLists
Lists
Sumit Tambe
 
Java for newcomers
Java for newcomersJava for newcomers
Java for newcomers
Amith jayasekara
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
Patrick Nicolas
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Julie Iskander
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Hyderabad Scalability Meetup
 
Applications of data structures
Applications of data structuresApplications of data structures
Applications of data structures
Wipro
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Lecture 19 matlab_script&function_files06
Lecture 19 matlab_script&function_files06Lecture 19 matlab_script&function_files06
Lecture 19 matlab_script&function_files06
Aman kazmi
 
Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template Library
Anirudh Raja
 
Introduction data structure
Introduction data structureIntroduction data structure
Introduction data structure
MUHAMMAD ISMAIL
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Martin Toshev
 
Cupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmCupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithm
TarikuDabala1
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
langer4711
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
icarter09
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
Patrick Nicolas
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Julie Iskander
 
Applications of data structures
Applications of data structuresApplications of data structures
Applications of data structures
Wipro
 

Viewers also liked (8)

OTS RoadShow 2016 – Θεσσαλονίκη: «Ηλεκτρονικές Εισπράξεις ΔΙΑΣ-Πάγιες Εντολές...
OTS RoadShow 2016 – Θεσσαλονίκη: «Ηλεκτρονικές Εισπράξεις ΔΙΑΣ-Πάγιες Εντολές...OTS RoadShow 2016 – Θεσσαλονίκη: «Ηλεκτρονικές Εισπράξεις ΔΙΑΣ-Πάγιες Εντολές...
OTS RoadShow 2016 – Θεσσαλονίκη: «Ηλεκτρονικές Εισπράξεις ΔΙΑΣ-Πάγιες Εντολές...
OTS SA
 
OTS RoadShow 2015 - Ρέθυμνο: ΜΕΡΙΜΝΑ
OTS RoadShow 2015 - Ρέθυμνο: ΜΕΡΙΜΝΑOTS RoadShow 2015 - Ρέθυμνο: ΜΕΡΙΜΝΑ
OTS RoadShow 2015 - Ρέθυμνο: ΜΕΡΙΜΝΑ
OTS SA
 
Math 1 Orientation Presentation
Math 1 Orientation PresentationMath 1 Orientation Presentation
Math 1 Orientation Presentation
Leo Crisologo
 
Πληροφορική
ΠληροφορικήΠληροφορική
Πληροφορική
Gymnasio Kokkinochorion
 
04 σύστημα αρχείων
04 σύστημα αρχείων04 σύστημα αρχείων
04 σύστημα αρχείων
Ιωάννου Γιαννάκης
 
06 εντολές clear cal date finger
06 εντολές clear cal date finger06 εντολές clear cal date finger
06 εντολές clear cal date finger
Ιωάννου Γιαννάκης
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
Dhammpal Ramtake
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab Introduction
ideas2ignite
 
OTS RoadShow 2016 – Θεσσαλονίκη: «Ηλεκτρονικές Εισπράξεις ΔΙΑΣ-Πάγιες Εντολές...
OTS RoadShow 2016 – Θεσσαλονίκη: «Ηλεκτρονικές Εισπράξεις ΔΙΑΣ-Πάγιες Εντολές...OTS RoadShow 2016 – Θεσσαλονίκη: «Ηλεκτρονικές Εισπράξεις ΔΙΑΣ-Πάγιες Εντολές...
OTS RoadShow 2016 – Θεσσαλονίκη: «Ηλεκτρονικές Εισπράξεις ΔΙΑΣ-Πάγιες Εντολές...
OTS SA
 
OTS RoadShow 2015 - Ρέθυμνο: ΜΕΡΙΜΝΑ
OTS RoadShow 2015 - Ρέθυμνο: ΜΕΡΙΜΝΑOTS RoadShow 2015 - Ρέθυμνο: ΜΕΡΙΜΝΑ
OTS RoadShow 2015 - Ρέθυμνο: ΜΕΡΙΜΝΑ
OTS SA
 
Math 1 Orientation Presentation
Math 1 Orientation PresentationMath 1 Orientation Presentation
Math 1 Orientation Presentation
Leo Crisologo
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab Introduction
ideas2ignite
 
Ad

Similar to Lecture 01 variables scripts and operations (20)

Mit6 094 iap10_lec01
Mit6 094 iap10_lec01Mit6 094 iap10_lec01
Mit6 094 iap10_lec01
Tribhuwan Pant
 
Matlab lec1
Matlab lec1Matlab lec1
Matlab lec1
Amba Research
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - IMatlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
joellivz
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
محمدعبد الحى
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
Mukesh Kumar
 
MATLAB for Engineers ME1006 (1 for beginer).pptx
MATLAB for Engineers ME1006 (1 for beginer).pptxMATLAB for Engineers ME1006 (1 for beginer).pptx
MATLAB for Engineers ME1006 (1 for beginer).pptx
lav8bell
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
SudhirNayak43
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
KrishnaChaitanya139768
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
ManasaChevula1
 
Matlab guide
Matlab guideMatlab guide
Matlab guide
aibad ahmed
 
Basic matlab for beginners
Basic matlab for beginnersBasic matlab for beginners
Basic matlab for beginners
Kwabena Owusu-Agyemang
 
matlab tutorial with separate function description and handson learning
matlab tutorial with separate function description and handson learningmatlab tutorial with separate function description and handson learning
matlab tutorial with separate function description and handson learning
vishalkumarpandey12
 
MATLAB INTRODUCTION
MATLAB INTRODUCTIONMATLAB INTRODUCTION
MATLAB INTRODUCTION
Dr. Krishna Mohbey
 
matlabchapter1.ppt
matlabchapter1.pptmatlabchapter1.ppt
matlabchapter1.ppt
PariaMotahari1
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
kebeAman
 
MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1
Elaf A.Saeed
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
MahuaPal6
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
AkashSingh728626
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - IMatlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
joellivz
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
Mukesh Kumar
 
MATLAB for Engineers ME1006 (1 for beginer).pptx
MATLAB for Engineers ME1006 (1 for beginer).pptxMATLAB for Engineers ME1006 (1 for beginer).pptx
MATLAB for Engineers ME1006 (1 for beginer).pptx
lav8bell
 
matlab tutorial with separate function description and handson learning
matlab tutorial with separate function description and handson learningmatlab tutorial with separate function description and handson learning
matlab tutorial with separate function description and handson learning
vishalkumarpandey12
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
kebeAman
 
MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1
Elaf A.Saeed
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
MahuaPal6
 
Ad

More from Smee Kaem Chann (20)

stress-and-strain
stress-and-strainstress-and-strain
stress-and-strain
Smee Kaem Chann
 
Robot khmer engineer
Robot khmer engineerRobot khmer engineer
Robot khmer engineer
Smee Kaem Chann
 
15 poteau-2
15 poteau-215 poteau-2
15 poteau-2
Smee Kaem Chann
 
14 poteau-1
14 poteau-114 poteau-1
14 poteau-1
Smee Kaem Chann
 
12 plancher-Eurocode 2
12 plancher-Eurocode 212 plancher-Eurocode 2
12 plancher-Eurocode 2
Smee Kaem Chann
 
Matlab_Prof Pouv Keangsé
Matlab_Prof Pouv KeangséMatlab_Prof Pouv Keangsé
Matlab_Prof Pouv Keangsé
Smee Kaem Chann
 
Vocabuary
VocabuaryVocabuary
Vocabuary
Smee Kaem Chann
 
Journal de bord
Journal de bordJournal de bord
Journal de bord
Smee Kaem Chann
 
8.4 roof leader
8.4 roof leader8.4 roof leader
8.4 roof leader
Smee Kaem Chann
 
Rapport de stage
Rapport de stage Rapport de stage
Rapport de stage
Smee Kaem Chann
 
Travaux Pratique Matlab + Corrige_Smee Kaem Chann
Travaux Pratique Matlab + Corrige_Smee Kaem ChannTravaux Pratique Matlab + Corrige_Smee Kaem Chann
Travaux Pratique Matlab + Corrige_Smee Kaem Chann
Smee Kaem Chann
 
Td triphasé
Td triphaséTd triphasé
Td triphasé
Smee Kaem Chann
 
Tp2 Matlab
Tp2 MatlabTp2 Matlab
Tp2 Matlab
Smee Kaem Chann
 
Cover matlab
Cover matlabCover matlab
Cover matlab
Smee Kaem Chann
 
New Interchange 3ed edition Vocabulary unit 8
New Interchange 3ed edition Vocabulary unit 8 New Interchange 3ed edition Vocabulary unit 8
New Interchange 3ed edition Vocabulary unit 8
Smee Kaem Chann
 
Matlab Travaux Pratique
Matlab Travaux Pratique Matlab Travaux Pratique
Matlab Travaux Pratique
Smee Kaem Chann
 
The technologies of building resists the wind load and earthquake
The technologies of building resists the wind load and earthquakeThe technologies of building resists the wind load and earthquake
The technologies of building resists the wind load and earthquake
Smee Kaem Chann
 
Devoir d'électricite des bêtiment
Devoir d'électricite des bêtimentDevoir d'électricite des bêtiment
Devoir d'électricite des bêtiment
Smee Kaem Chann
 
Rapport topographie 2016-2017
Rapport topographie 2016-2017  Rapport topographie 2016-2017
Rapport topographie 2016-2017
Smee Kaem Chann
 
Case study: Probability and Statistic
Case study: Probability and StatisticCase study: Probability and Statistic
Case study: Probability and Statistic
Smee Kaem Chann
 
Matlab_Prof Pouv Keangsé
Matlab_Prof Pouv KeangséMatlab_Prof Pouv Keangsé
Matlab_Prof Pouv Keangsé
Smee Kaem Chann
 
Travaux Pratique Matlab + Corrige_Smee Kaem Chann
Travaux Pratique Matlab + Corrige_Smee Kaem ChannTravaux Pratique Matlab + Corrige_Smee Kaem Chann
Travaux Pratique Matlab + Corrige_Smee Kaem Chann
Smee Kaem Chann
 
New Interchange 3ed edition Vocabulary unit 8
New Interchange 3ed edition Vocabulary unit 8 New Interchange 3ed edition Vocabulary unit 8
New Interchange 3ed edition Vocabulary unit 8
Smee Kaem Chann
 
Matlab Travaux Pratique
Matlab Travaux Pratique Matlab Travaux Pratique
Matlab Travaux Pratique
Smee Kaem Chann
 
The technologies of building resists the wind load and earthquake
The technologies of building resists the wind load and earthquakeThe technologies of building resists the wind load and earthquake
The technologies of building resists the wind load and earthquake
Smee Kaem Chann
 
Devoir d'électricite des bêtiment
Devoir d'électricite des bêtimentDevoir d'électricite des bêtiment
Devoir d'électricite des bêtiment
Smee Kaem Chann
 
Rapport topographie 2016-2017
Rapport topographie 2016-2017  Rapport topographie 2016-2017
Rapport topographie 2016-2017
Smee Kaem Chann
 
Case study: Probability and Statistic
Case study: Probability and StatisticCase study: Probability and Statistic
Case study: Probability and Statistic
Smee Kaem Chann
 

Recently uploaded (20)

Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT StrategyRisk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
john823664
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
UXPA Boston
 
Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.
marketing943205
 
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Vasileios Komianos
 
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UXPA Boston
 
Best 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat PlatformsBest 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat Platforms
Soulmaite
 
AI needs Hybrid Cloud - TEC conference 2025.pptx
AI needs Hybrid Cloud - TEC conference 2025.pptxAI needs Hybrid Cloud - TEC conference 2025.pptx
AI needs Hybrid Cloud - TEC conference 2025.pptx
Shikha Srivastava
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Understanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdfUnderstanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdf
Fulcrum Concepts, LLC
 
Scientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal DomainsScientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal Domains
syedanidakhader1
 
Secondary Storage for a microcontroller system
Secondary Storage for a microcontroller systemSecondary Storage for a microcontroller system
Secondary Storage for a microcontroller system
fizarcse
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
AI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández VallejoAI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández Vallejo
UXPA Boston
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT StrategyRisk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
john823664
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
UXPA Boston
 
Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.
marketing943205
 
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Vasileios Komianos
 
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UXPA Boston
 
Best 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat PlatformsBest 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat Platforms
Soulmaite
 
AI needs Hybrid Cloud - TEC conference 2025.pptx
AI needs Hybrid Cloud - TEC conference 2025.pptxAI needs Hybrid Cloud - TEC conference 2025.pptx
AI needs Hybrid Cloud - TEC conference 2025.pptx
Shikha Srivastava
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Understanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdfUnderstanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdf
Fulcrum Concepts, LLC
 
Scientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal DomainsScientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal Domains
syedanidakhader1
 
Secondary Storage for a microcontroller system
Secondary Storage for a microcontroller systemSecondary Storage for a microcontroller system
Secondary Storage for a microcontroller system
fizarcse
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
AI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández VallejoAI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández Vallejo
UXPA Boston
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 

Lecture 01 variables scripts and operations

  • 1. 6.094 Introduction to Programming in MATLAB Danilo Šćepanović IAP 2010 Lecture 1: Variables, Scripts, and Operations
  • 2. Course Layout • Lectures 1: Variables, Scripts and Operations 2: Visualization and Programming 3: Solving Equations, Fitting 4: Images, Animations, Advanced Methods 5: Optional: Symbolic Math, Simulink
  • 3. Outline (1) Getting Started (2) Scripts (3) Making Variables (4) Manipulating Variables (5) Basic Plotting
  • 4. Command Window Current directory Workspace Command History Courtesy of The MathWorks, Inc. Used with permission.
  • 5. Making Folders • Use folders to keep your programs organized • To make a new folder, click the ‘Browse’ button next to ‘Current Directory’ • Click the ‘Make New Folder’ button, and change the name of the folder. Do NOT use spaces in folder names. In the MATLAB folder, make two new folders: IAPMATLABday1 • Highlight the folder you just made and click ‘OK’ • The current directory is now the folder you just created • To see programs outside the current directory, they should be in the Path. Use File-> Set Path to add folders to the path
  • 6. Customization • File Preferences Allows you personalize your MATLAB experience Courtesy of The MathWorks, Inc. Used with permission.
  • 7. MATLAB Basics • MATLAB can be thought of as a super-powerful graphing calculator Remember the TI-83 from calculus? With many more buttons (built-in functions) • In addition it is a programming language MATLAB is an interpreted language, like Java Commands executed line by line
  • 8. Help/Docs • help The most important function for learning MATLAB on your own • To get info on how to use a function: » help sin Help lists related functions at the bottom and links to the doc • To get a nicer version of help with examples and easy-to- read descriptions: » doc sin • To search for a function by specifying keywords: » doc + Search tab
  • 9. Outline (1) Getting Started (2) Scripts (3) Making Variables (4) Manipulating Variables (5) Basic Plotting
  • 10. Scripts: Overview • Scripts are collection of commands executed in sequence written in the MATLAB editor saved as MATLAB files (.m extension) • To create an MATLAB file from command-line » edit helloWorld.m • or click Courtesy of The MathWorks, Inc. Used with permission.
  • 11. Scripts: the Editor * Means that it's not saved Line numbers Comments MATLAB file path Help file Possible breakpoints Debugging tools Real-time error check Courtesy of The MathWorks, Inc. Used with permission.
  • 12. Scripts: Some Notes • COMMENT! Anything following a % is seen as a comment The first contiguous comment becomes the script's help file Comment thoroughly to avoid wasting time later • Note that scripts are somewhat static, since there is no input and no explicit output • All variables created and modified in a script exist in the workspace even after it has stopped running
  • 13. Exercise: Scripts Make a helloWorld script • When run, the script should display the following text: • Hint: use disp to display strings. Strings are written between single quotes, like 'This is a string' Hello World! I am going to learn MATLAB!
  • 14. Outline (1) Getting Started (2) Scripts (3) Making Variables (4) Manipulating Variables (5) Basic Plotting
  • 15. Variable Types • MATLAB is a weakly typed language No need to initialize variables! • MATLAB supports various types, the most often used are » 3.84 64-bit double (default) » ‘a’ 16-bit char • Most variables you’ll deal with will be vectors or matrices of doubles or chars • Other types are also supported: complex, symbolic, 16-bit and 8 bit integers, etc. You will be exposed to all these types through the homework
  • 16. Naming variables • To create a variable, simply assign a value to a name: » var1=3.14 » myString=‘hello world’ • Variable names first character must be a LETTER after that, any combination of letters, numbers and _ CASE SENSITIVE! (var1 is different from Var1) • Built-in variables. Don’t use these names! i and j can be used to indicate complex numbers pi has the value 3.1415926… ans stores the last unassigned value (like on a calculator) Inf and -Inf are positive and negative infinity NaN represents ‘Not a Number’
  • 17. Scalars • A variable can be given a value explicitly » a = 10 shows up in workspace! • Or as a function of explicit values and existing variables » c = 1.3*45-2*a • To suppress output, end the line with a semicolon » cooldude = 13/3;
  • 18. Arrays • Like other programming languages, arrays are an important part of MATLAB • Two types of arrays (1) matrix of numbers (either double or complex) (2) cell array of objects (more advanced data structure) MATLAB makes vectors easy! That’s its power!
  • 19. Row Vectors • Row vector: comma or space separated values between brackets » row = [1 2 5.4 -6.6] » row = [1, 2, 5.4, -6.6]; • Command window: • Workspace: Courtesy of The MathWorks, Inc. Used with permission.
  • 20. Column Vectors • Column vector: semicolon separated values between brackets » column = [4;2;7;4] • Command window: • Workspace: Courtesy of The MathWorks, Inc. Used with permission.
  • 21. size & length • You can tell the difference between a row and a column vector by: Looking in the workspace Displaying the variable in the command window Using the size function • To get a vector's length, use the length function
  • 22. Matrices • Make matrices like vectors • Element by element » a= [1 2;3 4]; • By concatenating vectors or matrices (dimension matters) » a = [1 2]; » b = [3 4]; » c = [5;6]; » d = [a;b]; » e = [d c]; » f = [[e e];[a b a]]; » str = ['Hello, I am ' 'John']; Strings are character vectors 1 2 3 4 a ⎡ ⎤ = ⎢ ⎥ ⎣ ⎦
  • 23. save/clear/load • Use save to save variables to a file » save myFile a b saves variables a and b to the file myfile.mat myfile.mat file is saved in the current directory Default working directory is » MATLAB Make sure you’re in the desired folder when saving files. Right now, we should be in: » MATLABIAPMATLABday1 • Use clear to remove variables from environment » clear a b look at workspace, the variables a and b are gone • Use load to load variable bindings into the environment » load myFile look at workspace, the variables a and b are back • Can do the same for entire environment » save myenv; clear all; load myenv;
  • 24. Exercise: Variables Get and save the current date and time • Create a variable start using the function clock • What is the size of start? Is it a row or column? • What does start contain? See help clock • Convert the vector start to a string. Use the function datestr and name the new variable startString • Save start and startString into a mat file named startTime
  • 25. Exercise: Variables Read in and display the current date and time • In helloWorld.m, read in the variables you just saved using load • Display the following text: • Hint: use the disp command again, and remember that strings are just vectors of characters so you can join two strings by making a row vector with the two strings as sub- vectors. I started learning MATLAB on *start date and time*
  • 26. Outline (1) Getting Started (2) Scripts (3) Making Variables (4) Manipulating Variables (5) Basic Plotting
  • 27. Basic Scalar Operations • Arithmetic operations (+,-,*,/) » 7/45 » (1+i)*(2+i) » 1 / 0 » 0 / 0 • Exponentiation (^) » 4^2 » (3+4*j)^2 • Complicated expressions, use parentheses » ((2+3)*3)^0.1 • Multiplication is NOT implicit given parentheses » 3(1+0.7) gives an error • To clear command window » clc
  • 28. Built-in Functions • MATLAB has an enormous library of built-in functions • Call using parentheses – passing parameter to function » sqrt(2) » log(2), log10(0.23) » cos(1.2), atan(-.8) » exp(2+4*i) » round(1.4), floor(3.3), ceil(4.23) » angle(i); abs(1+i);
  • 29. Exercise: Scalars You will learn MATLAB at an exponential rate! Add the following to your helloWorld script: • Your learning time constant is 1.5 days. Calculate the number of seconds in 1.5 days and name this variable tau • This class lasts 5 days. Calculate the number of seconds in 5 days and name this variable endOfClass • This equation describes your knowledge as a function of time t: • How well will you know MATLAB at endOfClass? Name this variable knowledgeAtEnd. (use exp) • Using the value of knowledgeAtEnd, display the phrase: • Hint: to convert a number to a string, use num2str / 1 t k e τ− = − At the end of 5 days, I will know X% of MATLAB
  • 30. Transpose • The transpose operators turns a column vector into a row vector and vice versa » a = [1 2 3 4+i] » transpose(a) » a' » a.' • The ' gives the Hermitian-transpose, i.e. transposes and conjugates all complex numbers • For vectors of real numbers .' and ' give same result
  • 31. Addition and Subtraction • Addition and subtraction are element-wise; sizes must match (unless one is a scalar): • The following would give an error » c = row + column • Use the transpose to make sizes compatible » c = row’ + column » c = row + column’ • Can sum up or multiply elements of vector » s=sum(row); » p=prod(row); [ ] [ ] [ ] 12 3 32 11 2 11 30 32 14 14 2 21 − + − = 12 3 9 1 1 2 10 13 23 0 33 33 ⎡ ⎤ ⎡ ⎤ ⎡ ⎤ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥−⎢ ⎥ ⎢ ⎥ ⎢ ⎥− = ⎢ ⎥ ⎢ ⎥ ⎢ ⎥− − ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ −⎣ ⎦ ⎣ ⎦ ⎣ ⎦
  • 32. Element-Wise Functions • All the functions that work on scalars also work on vectors » t = [1 2 3]; » f = exp(t); is the same as » f = [exp(1) exp(2) exp(3)]; • If in doubt, check a function’s help file to see if it handles vectors elementwise • Operators (* / ^) have two modes of operation element-wise standard
  • 33. Operators: element-wise • To do element-wise operations, use the dot: . (.*, ./, .^). BOTH dimensions must match (unless one is scalar)! » a=[1 2 3];b=[4;2;1]; » a.*b, a./b, a.^b all errors » a.*b', a./b’, a.^(b’) all valid [ ] 4 1 2 3 2 1 1 4 4 2 2 4 3 1 3 3 1 3 1 3 1 .* ERROR .* .* ⎡ ⎤ ⎢ ⎥ =⎢ ⎥ ⎢ ⎥⎣ ⎦ ⎡ ⎤ ⎡ ⎤ ⎡ ⎤ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥=⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎣ ⎦ ⎣ ⎦ ⎣ ⎦ × × = × 1 1 1 1 2 3 1 2 3 2 2 2 1 2 3 2 4 6 3 3 3 1 2 3 3 6 9 3 3 3 3 3 3 .* .* ⎡ ⎤ ⎡ ⎤ ⎡ ⎤ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥=⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎣ ⎦ ⎣ ⎦ ⎣ ⎦ × × = × 2 2 2 2 1 2 1 2 2 3 4 3 4 .^ Can be any dimension ⎡ ⎤⎡ ⎤ = ⎢ ⎥⎢ ⎥ ⎣ ⎦ ⎣ ⎦
  • 34. Operators: standard • Multiplication can be done in a standard way or element-wise • Standard multiplication (*) is either a dot-product or an outer- product Remember from linear algebra: inner dimensions must MATCH!! • Standard exponentiation (^) can only be done on square matrices or scalars • Left and right division (/ ) is same as multiplying by inverse Our recommendation: just multiply by inverse (more on this later) [ ] 4 1 2 3 2 11 1 1 3 3 1 1 1 * * ⎡ ⎤ ⎢ ⎥ =⎢ ⎥ ⎢ ⎥⎣ ⎦ × × = × 1 1 1 1 2 3 3 6 9 2 2 2 1 2 3 6 12 18 3 3 3 1 2 3 9 18 27 3 3 3 3 3 3 * * ⎡ ⎤ ⎡ ⎤ ⎡ ⎤ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥=⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎣ ⎦ ⎣ ⎦ ⎣ ⎦ × × = × 1 2 1 2 1 2 2 3 4 3 4 3 4 ^ * Must be square to do powers ⎡ ⎤ ⎡ ⎤ ⎡ ⎤ =⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎣ ⎦ ⎣ ⎦ ⎣ ⎦
  • 35. Exercise: Vector Operations Calculate how many seconds elapsed since the start of class • In helloWorld.m, make variables called secPerMin, secPerHour, secPerDay, secPerMonth (assume 30.5 days per month), and secPerYear (12 months in year), which have the number of seconds in each time period. • Assemble a row vector called secondConversion that has elements in this order: secPerYear, secPerMonth, secPerDay, secPerHour, secPerMinute, 1. • Make a currentTime vector by using clock • Compute elapsedTime by subtracting currentTime from start • Compute t (the elapsed time in seconds) by taking the dot product of secondConversion and elapsedTime (transpose one of them to get the dimensions right)
  • 36. Exercise: Vector Operations Display the current state of your knowledge • Calculate currentKnowledge using the same relationship as before, and the t we just calculated: • Display the following text: / 1 t k e τ− = − At this time, I know X% of MATLAB
  • 37. Automatic Initialization • Initialize a vector of ones, zeros, or random numbers » o=ones(1,10) row vector with 10 elements, all 1 » z=zeros(23,1) column vector with 23 elements, all 0 » r=rand(1,45) row vector with 45 elements (uniform [0,1]) » n=nan(1,69) row vector of NaNs (useful for representing uninitialized variables) The general function call is: var=zeros(M,N); Number of rows Number of columns
  • 38. Automatic Initialization • To initialize a linear vector of values use linspace » a=linspace(0,10,5) starts at 0, ends at 10 (inclusive), 5 values • Can also use colon operator (:) » b=0:2:10 starts at 0, increments by 2, and ends at or before 10 increment can be decimal or negative » c=1:5 if increment isn’t specified, default is 1 • To initialize logarithmically spaced values use logspace similar to linspace, but see help
  • 39. Exercise: Vector Functions Calculate your learning trajectory • In helloWorld.m, make a linear time vector tVec that has 10,000 samples between 0 and endOfClass • Calculate the value of your knowledge (call it knowledgeVec) at each of these time points using the same equation as before: / 1 t k e τ− = −
  • 40. Vector Indexing • MATLAB indexing starts with 1, not 0 We will not respond to any emails where this is the problem. • a(n) returns the nth element • The index argument can be a vector. In this case, each element is looked up individually, and returned as a vector of the same size as the index vector. » x=[12 13 5 8]; » a=x(2:3); a=[13 5]; » b=x(1:end-1); b=[12 13 5]; [ ]13 5 9 10a = a(1) a(2) a(3) a(4)
  • 41. Matrix Indexing • Matrices can be indexed in two ways using subscripts (row and column) using linear indices (as if matrix is a vector) • Matrix indexing: subscripts or linear indices • Picking submatrices » A = rand(5) % shorthand for 5x5 matrix » A(1:3,1:2) % specify contiguous submatrix » A([1 5 3], [1 4]) % specify rows and columns 14 33 9 8 ⎡ ⎤ ⎢ ⎥ ⎣ ⎦ b(1) b(2) b(3) b(4) 14 33 9 8 ⎡ ⎤ ⎢ ⎥ ⎣ ⎦ b(1,1) b(2,1) b(1,2) b(2,2)
  • 42. Advanced Indexing 1 • To select rows or columns of a matrix, use the : » d=c(1,:); d=[12 5]; » e=c(:,2); e=[5;13]; » c(2,:)=[3 6]; %replaces second row of c 12 5 2 13 c ⎡ ⎤ = ⎢ ⎥−⎣ ⎦
  • 43. Advanced Indexing 2 • MATLAB contains functions to help you find desired values within a vector or matrix » vec = [5 3 1 9 7] • To get the minimum value and its index: » [minVal,minInd] = min(vec); max works the same way • To find any the indices of specific values or ranges » ind = find(vec == 9); » ind = find(vec > 2 & vec < 6); find expressions can be very complex, more on this later • To convert between subscripts and indices, use ind2sub, and sub2ind. Look up help to see how to use them.
  • 44. Exercise: Indexing When will you know 50% of MATLAB? • First, find the index where knowledgeVec is closest to 0.5. Mathematically, what you want is the index where the value of is at a minimum (use abs and min). • Next, use that index to look up the corresponding time in tVec and name this time halfTime. • Finally, display the string: Convert halfTime to days by using secPerDay 0.5knowledgeVec − I will know half of MATLAB after X days
  • 45. Outline (1) Getting Started (2) Scripts (3) Making Variables (4) Manipulating Variables (5) Basic Plotting Did everyone sign in?
  • 46. Plotting • Example » x=linspace(0,4*pi,10); » y=sin(x); • Plot values against their index » plot(y); • Usually we want to plot y versus x » plot(x,y); MATLAB makes visualizing data fun and easy!
  • 47. What does plot do? • plot generates dots at each (x,y) pair and then connects the dots with a line • To make plot of a function look smoother, evaluate at more points » x=linspace(0,4*pi,1000); » plot(x,sin(x)); • x and y vectors must be same size or else you’ll get an error » plot([1 2], [1 2 3]) error!! 10 x values: 0 2 4 6 8 10 12 14 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 0 2 4 6 8 10 12 14 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 1000 x values:
  • 48. Exercise: Plotting Plot the learning trajectory • In helloWorld.m, open a new figure (use figure) • Plot the knowledge trajectory using tVec and knowledgeVec. When plotting, convert tVec to days by using secPerDay • Zoom in on the plot to verify that halfTime was calculated correctly
  • 49. End of Lecture 1 (1) Getting Started (2) Scripts (3) Making Variables (4) Manipulating Variables (5) Basic Plotting Hope that wasn’t too much!!
  • 50. MIT OpenCourseWare http://ocw.mit.edu 6.094 Introduction to MATLAB® January (IAP) 2010 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.