SlideShare a Scribd company logo
1 of 34
Download to read offline
6.094

Introduction to programming in MATLAB

Lecture 4: Advanced Methods

Danilo Šćepanović
IAP 2010
Homework 3 Recap
• How long did it take?
• Common issues:
• The ODE file should be separate from the command that
solves it. ie. you should not be calling ode45 from within
your ODE file
• The structure of the output of an ode solver is to have time
running down the columns, so each column of y is a
variable, and the last row of y are the last values
• HW 4 was updated today, so download it again if you
already started. Show a juliaAnimation
• Today is the last required class: make sure the sign-in
sheet is accurate regarding your credit/listener status
Outline
(1)
(2)
(3)
(4)
(5)

Probability and Statistics
Data Structures
Images and Animation
Debugging
Online Resources
Statistics
• Whenever analyzing data, you have to compute statistics
» scores = 100*rand(1,100);
• Built-in functions
mean, median, mode

• To group data into a histogram
» hist(scores,5:10:95);
makes a histogram with bins centered at 5, 15, 25…95

» N=histc(scores,0:10:100);
returns the number of occurrences between the specified
bin edges 0 to <10, 10 to <20…90 to <100. you can plot
these manually:

» bar(0:10:100,N,'r')
Random Numbers
• Many probabilistic processes rely on random numbers
• MATLAB contains the common distributions built in
» rand
draws from the uniform distribution from 0 to 1

» randn
draws from the standard normal distribution (Gaussian)

» random
can give random numbers from many more distributions
see doc random for help
the docs also list other specific functions

• You can also seed the random number generators
» rand('state',0); rand(1); rand(1);
rand('state',0); rand(1);
Changing Mean and Variance
• We can alter the given distributions
» y=rand(1,100)*10+5;
gives 100 uniformly distributed numbers between 5 and 15

» y=floor(rand(1,100)*10+6);
gives 100 uniformly distributed integers between 10 and
15. floor or ceil is better to use here than round
400
350

» y=randn(1,1000)
» y2=y*5+8
increases std to 5 and makes the mean 8

300
250
200
150
100
50
0
-25

-20

-15

-10

-5

0

5

10

15

20

25

-20

-15

-10

-5

0

5

10

15

20

25

90
80
70
60
50
40
30
20
10
0
-25
Exercise: Probability
• We will simulate Brownian motion in 1 dimension. Call the script
‘brown’
• Make a 10,000 element vector of zeros
• Write a loop to keep track of the particle’s position at each time
• Start at 0. To get the new position, pick a random number, and if
it’s <0.5, go left; if it’s >0.5, go right. Store each new position in
the kth position in the vector
• Plot a 50 bin histogram of the positions.
Exercise: Probability
• We will simulate Brownian motion in 1 dimension. Call the script
‘brown’
• Make a 10,000 element vector of zeros
• Write a loop to keep track of the particle’s position at each time
• Start at 0. To get the new position, pick a random number, and if
it’s <0.5, go left; if it’s >0.5, go right. Store each new position in
the kth position in the vector
• Plot a 50 bin histogram of the positions.
»
»
»
»
»
»
»
»
»
»

x=zeros(10000,1);
for n=2:10000
if rand<0.5
x(n)=x(n-1)-1;
else
x(n)=x(n-1)+1;
end
end
figure;
hist(x,50);
Outline
(1)
(2)
(3)
(4)
(5)

Probability and Statistics
Data Structures
Images and Animation
Debugging
Online Resources
Advanced Data Structures
• We have used 2D matrices
Can have n-dimensions
Every element must be the same type (ex. integers,
doubles, characters…)
Matrices are space-efficient and convenient for calculation
Large matrices with many zeros can be made sparse:
» a=zeros(100); a(1,3)=10;a(21,5)=pi; b=sparse(a);

• Sometimes, more complex data structures are more
appropriate
Cell array: it's like an array, but elements don't have to
be the same type
Structs: can bundle variable names and values into one
structure
– Like object oriented programming in MATLAB
Cells: organization
• A cell is just like a matrix, but each field can contain
anything (even other matrices):
3x3 Cell Array

3x3 Matrix
J o
1.2

-3

5.5

-2.4

15

-10

7.8

-1.1

h n

4

4

32

M a r y

27

2

1

18

L e o

[]

• One cell can contain people's names, ages, and the ages of
their children
• To do the same with matrices, you would need 3 variables
and padding
Cells: initialization
• To initialize a cell, specify the size
» a=cell(3,10);
a will be a cell with 3 rows and 10 columns

• or do it manually, with curly braces {}
» c={'hello world',[1 5 6 2],rand(3,2)};
c is a cell with 1 row and 3 columns

• Each element of a cell can be anything
• To
»
»
»

access a cell element, use curly braces {}
a{1,1}=[1 3 4 -10];
a{2,1}='hello world 2';
a{1,2}=c{3};
Structs
• Structs allow you to name and bundle relevant variables
Like C-structs, which are objects with fields

• To initialize an empty struct:
» s=struct([]);
size(s) will be 1x1
initialization is optional but is recommended when using large
structs

• To
»
»
»

add fields
s.name = 'Jack Bauer';
s.scores = [95 98 67];
s.year = 'G3';
Fields can be anything: matrix, cell, even struct
Useful for keeping variables together

• For more information, see doc struct
Struct Arrays
•

To initialize a struct array, give field, values pairs
» ppl=struct('name',{'John','Mary','Leo'},...
'age',{32,27,18},'childAge',{[2;4],1,[]});
size(s2)=1x3
every cell must have the same size

» person=ppl(2);
person is now a struct with fields name, age, children
the values of the fields are the second index into each cell

» person.name
returns 'Mary'

ppl

ppl(1)

ppl(2)

ppl(3)

name:

'John'

'Mary'

'Leo'

age:

32

27

18

childAge:

[2;4]

1

[]

» ppl(1).age
returns 32
Structs: access
• To access 1x1 struct fields, give name of the field
» stu=s.name;
» scor=s.scores;
1x1 structs are useful when passing many variables to a
function. put them all in a struct, and pass the struct

• To access nx1 struct arrays, use indices
» person=ppl(2);
person is a struct with name, age, and child age

» personName=ppl(2).name;
personName is 'Mary'

» a=[ppl.age];
a is a 1x3 vector of the ages; this may not always work,
the vectors must be able to be concatenated.
Exercise: Cells
• Write a script called sentGen
• Make a 3x2 cell, and put three names into the first column,
and adjectives into the second column
• Pick two random integers (values 1 to 3)
• Display a sentence of the form '[name] is [adjective].'
• Run the script a few times
Exercise: Cells
• Write a script called sentGen
• Make a 3x2 cell, and put three names into the first column,
and adjectives into the second column
• Pick two random integers (values 1 to 3)
• Display a sentence of the form '[name] is [adjective].'
• Run the script a few times
»
»
»
»
»

c=cell(3,2);
c{1,1}=‘John’;c{2,1}=‘Mary-Sue’;c{3,1}=‘Gomer’;
c{1,2}=‘smart’;c{2,2}=‘blonde’;c{3,2}=‘hot’
r1=ceil(rand*3);r2=ceil(rand*3);
disp([ c{r1,1}, ' is ', c{r2,2}, '.' ]);
Outline
(1)
(2)
(3)
(4)
(5)

Probability and Statistics
Data Structures
Images and Animation
Debugging
Online Resources
Figure Handles
• Every graphics object has a handle
» L=plot(1:10,rand(1,10));
gets the handle for the plotted line

» A=gca;
gets the handle for the current axis

» F=gcf;
gets the handle for the current figure

• To see the current property values, use get
» get(L);
» yVals=get(L,'YData');
• To change the properties, use set
» set(A,'FontName','Arial','XScale','log');
» set(L,'LineWidth',1.5,'Marker','*');
• Everything you see in a figure is completely customizable
through handles
Reading/Writing Images
• Images can be imported into matlab
» im=imread('myPic.jpg');
• MATLAB supports almost all image formats
jpeg, tiff, gif, bmp, png, hdf, pcx, xwd, ico, cur, ras, pbm,
pgm, ppm
see help imread for a full list and details

• To write an image, give an rgb matrix or indices and
colormap
» imwrite(rand(300,300,3),'test1.jpg');
» imwrite(ceil(rand(200)*256),jet(256),...
'test2.jpg');
see help imwrite for more options
Animations
• MATLAB makes it easy to capture movie frames and play
them back automatically
• The most common movie formats are:
avi
animated gif

• Avi
good when you have ‘natural’ frames with lots of colors and
few clearly defined edges

• Animated gif
Good for making movies of plots or text where only a few
colors exist (limited to 256) and there are well-defined
lines
Making Animations
• Plot frame by frame, and pause in between
» close all
» for t=1:30
»
imagesc(rand(200));
»
colormap(gray);
»
pause(.5);
» end
• Can also use drawnow instead of pause
• When plotting lines or points, it's faster to change the
xdata and ydata properties rather than plotting each time
» h=plot(1:10,1:10);
» set(h,'ydata',10:1);
Saving Animations as Movies
• A movie is a series of captured frames
» close all
» for n=1:30
»
imagesc(rand(200));
»
colormap(gray);
»
M(n)=getframe;
» end
• To play a movie in a figure window
» movie(M,2,30);
Loops the movie 2 times at 30 frames per second

• To save as an .avi file on your hard drive
» movie2avi(M,'testMovie.avi','FPS',30, ...
'compression', 'cinepak');
• See doc movie2avi for more information
Making Animated GIFs
• You can use imwrite to save an animated GIF. Below is a
trivial example
» temp=ceil(rand(300,300,1,10)*256);
» imwrite(temp,jet(256),'testGif.gif',...
'delaytime',0.1,'loopcount',100);
• Alternatively, you can use getframe, frame2im, and
rgb2ind to convert any plotted figure to an indexed image
and then stack these indexed images into a 4-D matrix and
pass them to imwrite. Read the doc on imwrite and these
other functions to figure out how to do this.
Outline
(1)
(2)
(3)
(4)
(5)

Probability and Statistics
Data Structures
Images and Animation
Debugging
Online Resources
display
• When debugging functions, use disp to print messages
» disp('starting loop')
» disp('loop is over')
disp prints the given string to the command window

• It's also helpful to show variable values
» disp(strcat(['loop iteration ',num2str(n)]));
strcat concatenates the given strings
Sometimes it's easier to just remove some semicolons
Debugging
• To use the debugger, set breakpoints
Click on – next to line numbers in MATLAB files
Each red dot that appears is a breakpoint
Run the program
The program pauses when it reaches a breakpoint
Use the command window to probe variables
Use the debugging buttons to control debugger

Clear breakpoint

Stop execution; exit

Step to next
Two breakpoints
Where the program is now
Courtesy of The MathWorks, Inc. Used with permission.
Exercise: Debugging
• Use the debugger to fix the errors in the following code:

Courtesy of The MathWorks, Inc. Used with permission.
Performance Measures
• It can be useful to know how long your code takes to run
To predict how long a loop will take
To pinpoint inefficient code

• You can time operations using tic/toc:
» tic
» CommandBlock1
» a=toc;
» CommandBlock2
» b=toc;
tic resets the timer
Each toc returns the current value in seconds
Can have multiple tocs per tic
Performance Measures
• For more complicated programs, use the profiler
» profile on
Turns on the profiler. Follow this with function calls

» profile viewer
Displays gui with stats on how long each subfunction took

Courtesy of The MathWorks, Inc. Used with permission.
Outline
(1)
(2)
(3)
(4)
(5)

Probability and Statistics
Data Structures
Images and Animation
Debugging
Online Resources
Central File Exchange
• The website – the MATLAB Central File Exchange!!
• Lots of people's code is there
• Tested and rated – use it to expand MATLAB's functionality
• http://www.mathworks.com/matlabcentral/
End of Lecture 4
(1)
(2)
(3)
(4)
(5)

Probability and Statistics
Data Structures
Images and Animation
Debugging
Online Resources
THE END
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.

More Related Content

What's hot

16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonAndrew Ferlitsch
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 
Machine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowMachine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowAndrew Ferlitsch
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersKimikazu Kato
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
Accelerating Random Forests in Scikit-Learn
Accelerating Random Forests in Scikit-LearnAccelerating Random Forests in Scikit-Learn
Accelerating Random Forests in Scikit-LearnGilles Louppe
 
Natural Language Processing (NLP)
Natural Language Processing (NLP)Natural Language Processing (NLP)
Natural Language Processing (NLP)Hichem Felouat
 
Towards typesafe deep learning in scala
Towards typesafe deep learning in scalaTowards typesafe deep learning in scala
Towards typesafe deep learning in scalaTongfei Chen
 
Gráficas en python
Gráficas en python Gráficas en python
Gráficas en python Jhon Valle
 
Optimization (DLAI D4L1 2017 UPC Deep Learning for Artificial Intelligence)
Optimization (DLAI D4L1 2017 UPC Deep Learning for Artificial Intelligence)Optimization (DLAI D4L1 2017 UPC Deep Learning for Artificial Intelligence)
Optimization (DLAI D4L1 2017 UPC Deep Learning for Artificial Intelligence)Universitat Politècnica de Catalunya
 
Tensor board
Tensor boardTensor board
Tensor boardSung Kim
 
Advanced matlab codigos matematicos
Advanced matlab codigos matematicosAdvanced matlab codigos matematicos
Advanced matlab codigos matematicosKmilo Bolaños
 
digital signal-processing-lab-manual
digital signal-processing-lab-manualdigital signal-processing-lab-manual
digital signal-processing-lab-manualAhmed Alshomi
 
Predict future time series forecasting
Predict future time series forecastingPredict future time series forecasting
Predict future time series forecastingHichem Felouat
 

What's hot (20)

16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in Python
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
Machine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowMachine Learning - Introduction to Tensorflow
Machine Learning - Introduction to Tensorflow
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
 
Dsp manual
Dsp manualDsp manual
Dsp manual
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Accelerating Random Forests in Scikit-Learn
Accelerating Random Forests in Scikit-LearnAccelerating Random Forests in Scikit-Learn
Accelerating Random Forests in Scikit-Learn
 
Natural Language Processing (NLP)
Natural Language Processing (NLP)Natural Language Processing (NLP)
Natural Language Processing (NLP)
 
Towards typesafe deep learning in scala
Towards typesafe deep learning in scalaTowards typesafe deep learning in scala
Towards typesafe deep learning in scala
 
Gráficas en python
Gráficas en python Gráficas en python
Gráficas en python
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Transfer Learning
Transfer LearningTransfer Learning
Transfer Learning
 
Optimization (DLAI D4L1 2017 UPC Deep Learning for Artificial Intelligence)
Optimization (DLAI D4L1 2017 UPC Deep Learning for Artificial Intelligence)Optimization (DLAI D4L1 2017 UPC Deep Learning for Artificial Intelligence)
Optimization (DLAI D4L1 2017 UPC Deep Learning for Artificial Intelligence)
 
Tensor board
Tensor boardTensor board
Tensor board
 
Dsp lab manual
Dsp lab manualDsp lab manual
Dsp lab manual
 
Advanced matlab codigos matematicos
Advanced matlab codigos matematicosAdvanced matlab codigos matematicos
Advanced matlab codigos matematicos
 
digital signal-processing-lab-manual
digital signal-processing-lab-manualdigital signal-processing-lab-manual
digital signal-processing-lab-manual
 
Predict future time series forecasting
Predict future time series forecastingPredict future time series forecasting
Predict future time series forecasting
 

Viewers also liked

DXN Bahawalpur Persentation
DXN Bahawalpur PersentationDXN Bahawalpur Persentation
DXN Bahawalpur PersentationNaveed Asghar
 
Reasons to Pay Attention
Reasons to Pay AttentionReasons to Pay Attention
Reasons to Pay Attentionvickomarsh
 
Digital hour presentation BB10
Digital hour presentation BB10Digital hour presentation BB10
Digital hour presentation BB10Industree spa
 
How to value price websites
How to value price websitesHow to value price websites
How to value price websitesBen Furfie
 
Argent Global Network Daily Ad Post method
 Argent Global Network Daily Ad Post method  Argent Global Network Daily Ad Post method
Argent Global Network Daily Ad Post method Aamir Awan
 
где птичка
где птичкагде птичка
где птичкаgelia050505
 
DXN Presentation By Aamir Javed Awan 03442117822
DXN Presentation By Aamir Javed Awan 03442117822DXN Presentation By Aamir Javed Awan 03442117822
DXN Presentation By Aamir Javed Awan 03442117822Aamir Awan
 

Viewers also liked (12)

Role of international architects building in Pakistan
Role of international architects building in Pakistan Role of international architects building in Pakistan
Role of international architects building in Pakistan
 
DXN Bahawalpur Persentation
DXN Bahawalpur PersentationDXN Bahawalpur Persentation
DXN Bahawalpur Persentation
 
Reasons to Pay Attention
Reasons to Pay AttentionReasons to Pay Attention
Reasons to Pay Attention
 
Digital hour presentation BB10
Digital hour presentation BB10Digital hour presentation BB10
Digital hour presentation BB10
 
Tipografia
TipografiaTipografia
Tipografia
 
How to value price websites
How to value price websitesHow to value price websites
How to value price websites
 
Argent Global Network Daily Ad Post method
 Argent Global Network Daily Ad Post method  Argent Global Network Daily Ad Post method
Argent Global Network Daily Ad Post method
 
Taza
TazaTaza
Taza
 
где птичка
где птичкагде птичка
где птичка
 
DXN Presentation By Aamir Javed Awan 03442117822
DXN Presentation By Aamir Javed Awan 03442117822DXN Presentation By Aamir Javed Awan 03442117822
DXN Presentation By Aamir Javed Awan 03442117822
 
Dxn
DxnDxn
Dxn
 
Dxn presentation
Dxn presentationDxn presentation
Dxn presentation
 

Similar to Mit6 094 iap10_lec04

Basics of Python
Basics of PythonBasics of Python
Basics of PythonEase3
 
Lecture 02 visualization and programming
Lecture 02   visualization and programmingLecture 02   visualization and programming
Lecture 02 visualization and programmingSmee Kaem Chann
 
COMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptxCOMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptximman gwu
 
Lec12-CS110 Computational Engineering
Lec12-CS110 Computational EngineeringLec12-CS110 Computational Engineering
Lec12-CS110 Computational EngineeringSri Harsha Pamu
 
The Roassal3 Visualization Engine
The Roassal3 Visualization EngineThe Roassal3 Visualization Engine
The Roassal3 Visualization EngineESUG
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdfMariappanR3
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
Oct8 - 131 slid
Oct8 - 131 slidOct8 - 131 slid
Oct8 - 131 slidTak Lee
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functionsjoellivz
 

Similar to Mit6 094 iap10_lec04 (20)

Lec4
Lec4Lec4
Lec4
 
Lec2
Lec2Lec2
Lec2
 
tick cross game
tick cross gametick cross game
tick cross game
 
Basics of Python
Basics of PythonBasics of Python
Basics of Python
 
Lecture 02 visualization and programming
Lecture 02   visualization and programmingLecture 02   visualization and programming
Lecture 02 visualization and programming
 
COMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptxCOMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptx
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
 
Lec 06
Lec 06Lec 06
Lec 06
 
Arrays
ArraysArrays
Arrays
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Lec12-CS110 Computational Engineering
Lec12-CS110 Computational EngineeringLec12-CS110 Computational Engineering
Lec12-CS110 Computational Engineering
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 
The Roassal3 Visualization Engine
The Roassal3 Visualization EngineThe Roassal3 Visualization Engine
The Roassal3 Visualization Engine
 
Basic practice of R
Basic practice of RBasic practice of R
Basic practice of R
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdf
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
 
Oct8 - 131 slid
Oct8 - 131 slidOct8 - 131 slid
Oct8 - 131 slid
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
Matlab lec1
Matlab lec1Matlab lec1
Matlab lec1
 

Recently uploaded

ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPCeline George
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 

Recently uploaded (20)

ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERP
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 

Mit6 094 iap10_lec04

  • 1. 6.094 Introduction to programming in MATLAB Lecture 4: Advanced Methods Danilo Šćepanović IAP 2010
  • 2. Homework 3 Recap • How long did it take? • Common issues: • The ODE file should be separate from the command that solves it. ie. you should not be calling ode45 from within your ODE file • The structure of the output of an ode solver is to have time running down the columns, so each column of y is a variable, and the last row of y are the last values • HW 4 was updated today, so download it again if you already started. Show a juliaAnimation • Today is the last required class: make sure the sign-in sheet is accurate regarding your credit/listener status
  • 3. Outline (1) (2) (3) (4) (5) Probability and Statistics Data Structures Images and Animation Debugging Online Resources
  • 4. Statistics • Whenever analyzing data, you have to compute statistics » scores = 100*rand(1,100); • Built-in functions mean, median, mode • To group data into a histogram » hist(scores,5:10:95); makes a histogram with bins centered at 5, 15, 25…95 » N=histc(scores,0:10:100); returns the number of occurrences between the specified bin edges 0 to <10, 10 to <20…90 to <100. you can plot these manually: » bar(0:10:100,N,'r')
  • 5. Random Numbers • Many probabilistic processes rely on random numbers • MATLAB contains the common distributions built in » rand draws from the uniform distribution from 0 to 1 » randn draws from the standard normal distribution (Gaussian) » random can give random numbers from many more distributions see doc random for help the docs also list other specific functions • You can also seed the random number generators » rand('state',0); rand(1); rand(1); rand('state',0); rand(1);
  • 6. Changing Mean and Variance • We can alter the given distributions » y=rand(1,100)*10+5; gives 100 uniformly distributed numbers between 5 and 15 » y=floor(rand(1,100)*10+6); gives 100 uniformly distributed integers between 10 and 15. floor or ceil is better to use here than round 400 350 » y=randn(1,1000) » y2=y*5+8 increases std to 5 and makes the mean 8 300 250 200 150 100 50 0 -25 -20 -15 -10 -5 0 5 10 15 20 25 -20 -15 -10 -5 0 5 10 15 20 25 90 80 70 60 50 40 30 20 10 0 -25
  • 7. Exercise: Probability • We will simulate Brownian motion in 1 dimension. Call the script ‘brown’ • Make a 10,000 element vector of zeros • Write a loop to keep track of the particle’s position at each time • Start at 0. To get the new position, pick a random number, and if it’s <0.5, go left; if it’s >0.5, go right. Store each new position in the kth position in the vector • Plot a 50 bin histogram of the positions.
  • 8. Exercise: Probability • We will simulate Brownian motion in 1 dimension. Call the script ‘brown’ • Make a 10,000 element vector of zeros • Write a loop to keep track of the particle’s position at each time • Start at 0. To get the new position, pick a random number, and if it’s <0.5, go left; if it’s >0.5, go right. Store each new position in the kth position in the vector • Plot a 50 bin histogram of the positions. » » » » » » » » » » x=zeros(10000,1); for n=2:10000 if rand<0.5 x(n)=x(n-1)-1; else x(n)=x(n-1)+1; end end figure; hist(x,50);
  • 9. Outline (1) (2) (3) (4) (5) Probability and Statistics Data Structures Images and Animation Debugging Online Resources
  • 10. Advanced Data Structures • We have used 2D matrices Can have n-dimensions Every element must be the same type (ex. integers, doubles, characters…) Matrices are space-efficient and convenient for calculation Large matrices with many zeros can be made sparse: » a=zeros(100); a(1,3)=10;a(21,5)=pi; b=sparse(a); • Sometimes, more complex data structures are more appropriate Cell array: it's like an array, but elements don't have to be the same type Structs: can bundle variable names and values into one structure – Like object oriented programming in MATLAB
  • 11. Cells: organization • A cell is just like a matrix, but each field can contain anything (even other matrices): 3x3 Cell Array 3x3 Matrix J o 1.2 -3 5.5 -2.4 15 -10 7.8 -1.1 h n 4 4 32 M a r y 27 2 1 18 L e o [] • One cell can contain people's names, ages, and the ages of their children • To do the same with matrices, you would need 3 variables and padding
  • 12. Cells: initialization • To initialize a cell, specify the size » a=cell(3,10); a will be a cell with 3 rows and 10 columns • or do it manually, with curly braces {} » c={'hello world',[1 5 6 2],rand(3,2)}; c is a cell with 1 row and 3 columns • Each element of a cell can be anything • To » » » access a cell element, use curly braces {} a{1,1}=[1 3 4 -10]; a{2,1}='hello world 2'; a{1,2}=c{3};
  • 13. Structs • Structs allow you to name and bundle relevant variables Like C-structs, which are objects with fields • To initialize an empty struct: » s=struct([]); size(s) will be 1x1 initialization is optional but is recommended when using large structs • To » » » add fields s.name = 'Jack Bauer'; s.scores = [95 98 67]; s.year = 'G3'; Fields can be anything: matrix, cell, even struct Useful for keeping variables together • For more information, see doc struct
  • 14. Struct Arrays • To initialize a struct array, give field, values pairs » ppl=struct('name',{'John','Mary','Leo'},... 'age',{32,27,18},'childAge',{[2;4],1,[]}); size(s2)=1x3 every cell must have the same size » person=ppl(2); person is now a struct with fields name, age, children the values of the fields are the second index into each cell » person.name returns 'Mary' ppl ppl(1) ppl(2) ppl(3) name: 'John' 'Mary' 'Leo' age: 32 27 18 childAge: [2;4] 1 [] » ppl(1).age returns 32
  • 15. Structs: access • To access 1x1 struct fields, give name of the field » stu=s.name; » scor=s.scores; 1x1 structs are useful when passing many variables to a function. put them all in a struct, and pass the struct • To access nx1 struct arrays, use indices » person=ppl(2); person is a struct with name, age, and child age » personName=ppl(2).name; personName is 'Mary' » a=[ppl.age]; a is a 1x3 vector of the ages; this may not always work, the vectors must be able to be concatenated.
  • 16. Exercise: Cells • Write a script called sentGen • Make a 3x2 cell, and put three names into the first column, and adjectives into the second column • Pick two random integers (values 1 to 3) • Display a sentence of the form '[name] is [adjective].' • Run the script a few times
  • 17. Exercise: Cells • Write a script called sentGen • Make a 3x2 cell, and put three names into the first column, and adjectives into the second column • Pick two random integers (values 1 to 3) • Display a sentence of the form '[name] is [adjective].' • Run the script a few times » » » » » c=cell(3,2); c{1,1}=‘John’;c{2,1}=‘Mary-Sue’;c{3,1}=‘Gomer’; c{1,2}=‘smart’;c{2,2}=‘blonde’;c{3,2}=‘hot’ r1=ceil(rand*3);r2=ceil(rand*3); disp([ c{r1,1}, ' is ', c{r2,2}, '.' ]);
  • 18. Outline (1) (2) (3) (4) (5) Probability and Statistics Data Structures Images and Animation Debugging Online Resources
  • 19. Figure Handles • Every graphics object has a handle » L=plot(1:10,rand(1,10)); gets the handle for the plotted line » A=gca; gets the handle for the current axis » F=gcf; gets the handle for the current figure • To see the current property values, use get » get(L); » yVals=get(L,'YData'); • To change the properties, use set » set(A,'FontName','Arial','XScale','log'); » set(L,'LineWidth',1.5,'Marker','*'); • Everything you see in a figure is completely customizable through handles
  • 20. Reading/Writing Images • Images can be imported into matlab » im=imread('myPic.jpg'); • MATLAB supports almost all image formats jpeg, tiff, gif, bmp, png, hdf, pcx, xwd, ico, cur, ras, pbm, pgm, ppm see help imread for a full list and details • To write an image, give an rgb matrix or indices and colormap » imwrite(rand(300,300,3),'test1.jpg'); » imwrite(ceil(rand(200)*256),jet(256),... 'test2.jpg'); see help imwrite for more options
  • 21. Animations • MATLAB makes it easy to capture movie frames and play them back automatically • The most common movie formats are: avi animated gif • Avi good when you have ‘natural’ frames with lots of colors and few clearly defined edges • Animated gif Good for making movies of plots or text where only a few colors exist (limited to 256) and there are well-defined lines
  • 22. Making Animations • Plot frame by frame, and pause in between » close all » for t=1:30 » imagesc(rand(200)); » colormap(gray); » pause(.5); » end • Can also use drawnow instead of pause • When plotting lines or points, it's faster to change the xdata and ydata properties rather than plotting each time » h=plot(1:10,1:10); » set(h,'ydata',10:1);
  • 23. Saving Animations as Movies • A movie is a series of captured frames » close all » for n=1:30 » imagesc(rand(200)); » colormap(gray); » M(n)=getframe; » end • To play a movie in a figure window » movie(M,2,30); Loops the movie 2 times at 30 frames per second • To save as an .avi file on your hard drive » movie2avi(M,'testMovie.avi','FPS',30, ... 'compression', 'cinepak'); • See doc movie2avi for more information
  • 24. Making Animated GIFs • You can use imwrite to save an animated GIF. Below is a trivial example » temp=ceil(rand(300,300,1,10)*256); » imwrite(temp,jet(256),'testGif.gif',... 'delaytime',0.1,'loopcount',100); • Alternatively, you can use getframe, frame2im, and rgb2ind to convert any plotted figure to an indexed image and then stack these indexed images into a 4-D matrix and pass them to imwrite. Read the doc on imwrite and these other functions to figure out how to do this.
  • 25. Outline (1) (2) (3) (4) (5) Probability and Statistics Data Structures Images and Animation Debugging Online Resources
  • 26. display • When debugging functions, use disp to print messages » disp('starting loop') » disp('loop is over') disp prints the given string to the command window • It's also helpful to show variable values » disp(strcat(['loop iteration ',num2str(n)])); strcat concatenates the given strings Sometimes it's easier to just remove some semicolons
  • 27. Debugging • To use the debugger, set breakpoints Click on – next to line numbers in MATLAB files Each red dot that appears is a breakpoint Run the program The program pauses when it reaches a breakpoint Use the command window to probe variables Use the debugging buttons to control debugger Clear breakpoint Stop execution; exit Step to next Two breakpoints Where the program is now Courtesy of The MathWorks, Inc. Used with permission.
  • 28. Exercise: Debugging • Use the debugger to fix the errors in the following code: Courtesy of The MathWorks, Inc. Used with permission.
  • 29. Performance Measures • It can be useful to know how long your code takes to run To predict how long a loop will take To pinpoint inefficient code • You can time operations using tic/toc: » tic » CommandBlock1 » a=toc; » CommandBlock2 » b=toc; tic resets the timer Each toc returns the current value in seconds Can have multiple tocs per tic
  • 30. Performance Measures • For more complicated programs, use the profiler » profile on Turns on the profiler. Follow this with function calls » profile viewer Displays gui with stats on how long each subfunction took Courtesy of The MathWorks, Inc. Used with permission.
  • 31. Outline (1) (2) (3) (4) (5) Probability and Statistics Data Structures Images and Animation Debugging Online Resources
  • 32. Central File Exchange • The website – the MATLAB Central File Exchange!! • Lots of people's code is there • Tested and rated – use it to expand MATLAB's functionality • http://www.mathworks.com/matlabcentral/
  • 33. End of Lecture 4 (1) (2) (3) (4) (5) Probability and Statistics Data Structures Images and Animation Debugging Online Resources THE END
  • 34. 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.