Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
GNU Octave Beginner's Guide

You're reading from  GNU Octave Beginner's Guide

Product type Book
Published in Jun 2011
Publisher Packt
ISBN-13 9781849513326
Pages 280 pages
Edition 1st Edition
Languages
Author (1):
Jesper Schmidt Hansen Jesper Schmidt Hansen
Profile icon Jesper Schmidt Hansen

Table of Contents (15) Chapters

GNU Octave
Credits
About the Author
About the Reviewers
1. www.PacktPub.com
2. Preface
1. Introducing GNU Octave 2. Interacting with Octave: Variables and Operators 3. Working with Octave: Functions and Plotting 4. Rationalizing: Octave Scripts 5. Extensions: Write Your Own Octave Functions 6. Making Your Own Package: A Poisson Equation Solver 7. More Examples: Data Analysis 8. Need for Speed: Optimization and Dynamically Linked Functions Pop quiz - Answers

Time for action - vectorizing the Monte Carlo integrator


Using the method above, the vectorized version of mcintgr is:

Code Listing 5.8
function I = mcintgrv(fun, a, b, mcloops) #1
#2
# Find maximum value of f #3
x = linspace(a,b); #4
f = feval(fun,x); #5
maxf = max(f); #6
#7
# Generating random arrays #8
r1 = rand(mcloops,1); #9
r2 = rand(mcloops,1); #10
#11
# Get random x and y values #12
l = b - a; #13
x = a + l.*r1; #14
y = maxf.*r2; #15
fx = feval(fun, x); #16
#17
# Counts the number of points that lie under the graph #18
counter = length(find(y<fx)); #19
#20
# The integral #21
I = counter/mcloops*maxf*l; #22
#23
endfunction #24

What just happened?

The vectorized function is called with the exact same inputs and outputs as mcintgr. The code should be straightforward to understand, perhaps except line 19. Here we first perform a comparison between the value of the function and the random points. This comparison operation results in a Boolean array which is passed to find, that returns...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}