No video

How to Perform Monte Carlo Integration in MATLAB | MATLAB Tutorial

  Рет қаралды 13,253

Phil Parisi

Phil Parisi

Күн бұрын

Пікірлер: 59
@philparisi_
@philparisi_ 2 жыл бұрын
Hey everyone! This version of the code does a For Loop because it is easier to understand the method at play. The faster version of the code is here: VECTORIZED VERSION OF CODE % Monte Carlo Integration % Vectorized Version - shorter and faster than what is shown in the video clc, clearvars, close all, format compact % This method optimizes performance over simplicity % Dots are not colored red and blue tic f = @(x) 10 + 5*sin(5*x); % Parameters N = 10000; a = 2; b = 4; M = 1.4*max(f(linspace(a,b))); % Generate Random Points x = rand(1,N)*(b-a) + a; y_val = rand(1,N)*M; % Perform Integral Calculation fx = f(x); PercentUnderCurve = sum(y_val REPLACE_WITH_LESS_THAN_SYMBOL fx) / N; Monte_Integral = PercentUnderCurve * M * (b-a) Matlab_Integral = integral(f,a,b) PercentError = abs(Monte_Integral-Matlab_Integral)/Matlab_Integral*100 toc % Plot plot(x,y_val','.') hold on plot(x,fx,'.')
@ZhoraPredator
@ZhoraPredator 3 ай бұрын
Thank You. You Helped Me For My LabWork.
@philparisi_
@philparisi_ 3 ай бұрын
Woohoo!! Glad to help. Check the pinned comment for the vectorized code as well, it runs faster
@ZhoraPredator
@ZhoraPredator 3 ай бұрын
@@philparisi_ Sure!
@liliosacole3289
@liliosacole3289 2 жыл бұрын
Hi Phil, I just found you and subscribed! I am excited to finally learn Matlab and be comfortable with it, I have always struggled. You might be the programming teacher I've been looking for. Thank you for such a structured, ellaborated, organized and excellent tutorial. Your teaching skills are unparalleled.
@philparisi_
@philparisi_ 2 жыл бұрын
Hi Lilosa! Wow, thank you so much for the kind words you have no idea how much that means to me! I appreciate the support. Right now, I'm working on a plotting series to fill out all the nooks and crannies of different types of plots. Next I'll be doing some basic image processing tutorials. I'm also looking for feedback so please let me know improvements to current videos as well as topics you would like to see and are interested in! Excited to have you on board :)
@liliosacole3289
@liliosacole3289 2 жыл бұрын
@@philparisi_ I look foward to learning and giving feedback. Thank you so much for sharing your work!
@philparisi_
@philparisi_ 2 жыл бұрын
@@liliosacole3289 awesome, so happy to have you on the journey :D I also just debuted a patreon page www.patreon.com/philsbeginnercode if you are at all interested in joining the community - still seeking that first patron haha. Keep commenting on the videos and I look forward to working with you!!
@alexarunyan
@alexarunyan 2 жыл бұрын
Thank you for teaching us all to be strong programmers!
@philparisi_
@philparisi_ 2 жыл бұрын
Monte Carlo would want it no other way...
@shehzadkhan7570
@shehzadkhan7570 Жыл бұрын
Simply Explained. More power to you man!
@philparisi_
@philparisi_ Жыл бұрын
Thanks for tuning in - glad you enjoyed it! Love me some numerical integration :)
@princysamuel5360
@princysamuel5360 Жыл бұрын
Thank you so much; That's a really good program and your explanations were so simple to understand.
@philparisi_
@philparisi_ Жыл бұрын
You are very welcome, thanks for tuning the channel. I’m working on more videos like this and if you’re interested consider subscribing :) happy coding!
@user-ny6mv1ve3x
@user-ny6mv1ve3x 2 жыл бұрын
Thank you so much! Very helpful for a specific project in my Univerisity!
@philparisi_
@philparisi_ 2 жыл бұрын
Awesome to hear! Thank you for watching. The channel is full of MATLAB tutorials with new videos every week (consider subscribing :D ). Have a great week!!
@rafaelpolo6023
@rafaelpolo6023 8 ай бұрын
Excellent. Thank you
@philparisi_
@philparisi_ 8 ай бұрын
You are very welcome Rafael! Thank you for tuning in and feel free to ask any questions
@rafaelpolo6023
@rafaelpolo6023 8 ай бұрын
You seem to know a lot about MATLAB, I ran into an obstacle. I am writing up a program in the GUI app on MATLAB that allows the user to move a slider from 1-100, the slider changes the number of rectangles that the user what's in order to calculate the differences in area of a specific function. There is an exact area editfield that does not change and the current area editfield does change when the slider changes. I have the code written up and it all works, I just need to input the rectangles under the curve that change with the slider count. I was wondering if you know the syntax for inputting shapes under a curve or anything similar to that? Thank you!
@philparisi_
@philparisi_ 8 ай бұрын
Great question!! Honestly, as this would take seeing your scripts for reference as well as visuals of what your GUI is doing… you should throw this into ChatGPT (or the MATLAB AI Playground). Copy and paste your code in, then explain what the errors are and what you want to do.
@nooraini6781
@nooraini6781 11 ай бұрын
Thanks a lot it was really a great video ...every step is explained in very detail...
@philparisi_
@philparisi_ 11 ай бұрын
You are very welcome! Glad you enjoyed it and I love helping programmers like yourself :)
@user-kg7id8hj9w
@user-kg7id8hj9w 2 жыл бұрын
Wooow 🤯 YOU ARE JUST AN AMAZING PROGRAMMER thanks a lot 🙏
@philparisi_
@philparisi_ 2 жыл бұрын
Haha thank you for bringing the energy to MATLAB! You might like a couple similar videos: Data Import & Visualize kzbin.info/www/bejne/i3TEe2WYacZ-fbM Fractal Geometry Algorithm kzbin.info/www/bejne/movFgmioftKmas0
@successor7851
@successor7851 2 жыл бұрын
Much thanks to you for this great tutorial.
@philparisi_
@philparisi_ 2 жыл бұрын
Awesome - glad you liked it! As always, let me know what other tutorials you‘d like to see 👍🏽
@amanvarshney51217
@amanvarshney51217 2 жыл бұрын
Thank you sir, very helpful
@philparisi_
@philparisi_ 2 жыл бұрын
Behind every successful man, there is a successful woman. Have a good one, Aman!
@theguitartist__
@theguitartist__ Жыл бұрын
nice explanation, just a question concerning the additional zeros part, i think we can remove them without the filter by using 2 additional variables (k=1 and j=1 before the loop) then: if y_val < fx under(k,1) = x_val; under(k,2) = y_val; k++; else above(j,1) = x_val; above(j,2) = y_val; j++; end
@philparisi_
@philparisi_ Жыл бұрын
Thank you Anis! There’s always more than one way to do something 👍🏽👍🏽
@philparisi_
@philparisi_ 2 жыл бұрын
Hey there! If you're serious about learning MATLAB, I just released a new online MATLAB training with 50+ videos! It has quizzes, tests, a final project, and you receive a certificate at the end! Check it out!!! trainings.internshala.com/matlab-training
@natalie1997927
@natalie1997927 2 жыл бұрын
Hi! can you make a matlab video of how to use Monte Carlo method to calculate the volume of a cone inscribed in the unit cube(L=1)?
@philparisi_
@philparisi_ 2 жыл бұрын
Hi Natalie, sounds like you want me to do your homework ;) I encourage you to think about how you would implement this... off the top of my head: 1. Draw random samples in the unit cube (x,y,z coordinates) 2. Keep samples that fall inside the cone of interest 3. Count samples that fall inside the cube vs. total samples drawn, this gives a percentage 4. Multiply percentage times the unit cube volume to get the volume of the cone! Watch the video another time, and with this direction you should be able to implement it! Let me know how it goes!
@cristiangorea9219
@cristiangorea9219 Жыл бұрын
Hello mr. Phil Parisi for the work done! I would like to ask you to help me with a model for the following request, it is a request to which I ask you to comply only if you consider it appropriate: Statistical methods for rapid identification (by randomly drawing values between 0 and 1) of a user's behavior (or the output of a distributed source) using the Monte Carlo method. Respectfully!
@philparisi_
@philparisi_ Жыл бұрын
Hi Cristian, thank you for reaching out! I am not entirely sure what it is you are trying to do… can you provide more details? You can randomly generate the values with rand() and do this iterate to imitate a user’s behavior. However I am not sure how this fits into the larger context of the problem you are trying to solve!
@vitosjacob4326
@vitosjacob4326 2 жыл бұрын
Hi very awesome video!! May i ask if this method can be used to find the area of a heart function and can you maybe give me some hints on how to do it, as i just started learning matlab. Thank you!
@philparisi_
@philparisi_ 2 жыл бұрын
Hi Vitos! Glad you enjoyed it. The heart function - can you be more specific? I'd guess this is a function that forms a heart, perhaps in polar coordinates? Keep in mind this video does integration -- are you trying to find area inside a heart or an integral? One is not always the other.
@vitosjacob4326
@vitosjacob4326 2 жыл бұрын
@@philparisi_ my teacher only gave me a heart equation by the form of : y= 13cos(t) - 4cos(2t) - 2cos(3t) - cos(4t) + 30 , 0
@vitosjacob4326
@vitosjacob4326 2 жыл бұрын
@@philparisi_ and x = 16sin^3(t) + 30
@philparisi_
@philparisi_ 2 жыл бұрын
​@@vitosjacob4326 looks about right! Seems like equation was converted from polar to cartesian, all good nonetheless. What you can try, is replace the equation I used in my video with the x and y that you want to use. Then when you generate the random points , plug the x into the y=f(x) and perform the check if y_rand < y_nominal (nominal coming from the heart equation - clearer in the video). Then do the same area calculation at the end that I did and you might be good! Hard for me to picture if this will work or not with the equation provided, but give it a go and see!
@vitosjacob4326
@vitosjacob4326 2 жыл бұрын
@@philparisi_ thank you very much for the tip!!
@ake_lindblom
@ake_lindblom 2 жыл бұрын
Just FYI Monte Carlo is a place not a person, great video btw!
@philparisi_
@philparisi_ 2 жыл бұрын
I'll be darned! Thank you for this nugget of wisdom. en.wikipedia.org/wiki/Monte_Carlo_method Brain baby of Neumann and Ulam, named after the Monte Carlo Casino in Monaco it sounds like!
@majorlightgaming2593
@majorlightgaming2593 Жыл бұрын
Hi! Really good explanation. I finally understand the purpose of monte carlo technique. Just wanted to ask how this method can be used to determine the number of circles (same radius) that can fit inside a square of any length. And the same thing for number of spheres in a cube. Just want some guidance as I'm unsure on how to start.
@philparisi_
@philparisi_ Жыл бұрын
Hi there, happy to help! If I am understanding correctly, you'd want to know - for example - how many circle of radius 2 could fit inside a square of side length 40? Using Monte Carlo techniques? Assuming no overlap of the inside shapes. So from my intuition, there is probably some formula that exists out there, but it would come from a complex mathematical proof. That would be your 'exact' answer, and the fitting of the circles would be very elegant. Monte Carlo will be messy, and will likely under predict the number of shapes that could fit inside the larger shape. Your algorithm would be setup as such: - define shape geometries - for loop from 1:5000 ... generate a random 'origin' point for your inner shapes bounded by the size of the outer shape ... 'place' a circle there, then keep track of that point because you don't want to place any other points nearby (a distance r away from the place circle origins is off limits) ... keep generating more origins until you haven't added a new origin for 100 loops or something end loop - count up the number of origin points you have and that's roughly the number of shapes you can fit! The main problem is that there will be inefficient placement, such as gap between shapes that cannot fit another shape in that gap so it is wasted space.
@majorlightgaming2593
@majorlightgaming2593 Жыл бұрын
@@philparisi_ the exact number would just be area of square divided by the area of each circle and rounding it down. I have tried using monte carlo for it but the numbers I get are really small like you said.
@majorlightgaming2593
@majorlightgaming2593 Жыл бұрын
@@philparisi_ just for counting the origin points. How can I put an argument for those? Sorry it is just very hard to visualize.
@philparisi_
@philparisi_ Жыл бұрын
@@majorlightgaming2593 not quite sure what you mean by 'put an argument for those', can you specify? One thing you could do to get closer would be to 'relax' the radius. So if you want to fit circles of r = 3, you could actually do circles of r = 2 and that might be you closer. If you want to create a visualization, when you go through the algorithm be sure to store all the origin points that work. Then, create a separate function that plots a circle with a radius. Do a for loop over all the origin points and pass the x,y origin coordinates as the arguments to the function. www.educba.com/matlab-plot-circle/
@majorlightgaming2593
@majorlightgaming2593 Жыл бұрын
@@philparisi_ I meant for the loop. For the point of origin I get, how should my code look like? For example, should I let the x and y coordinates be less than the radius? Just need help with the loop part. Other than that, your explanation was solid 👍
@piotrosika7041
@piotrosika7041 Жыл бұрын
it dosent work if tej function is under x axis (y>0)
@philparisi_
@philparisi_ Жыл бұрын
Hi Piotr, you would need to adjust the code when you calculate the area of the 'block' where you spawn the random points. Instead of "Max_Height - 0" you need to do "Max_Height - Min_Height" and probably a couple other minor tweaks. The algorithm is certainly still valid.
@Farzamkhv
@Farzamkhv Жыл бұрын
Just a quick question, this example, is not just for the graph but the graph is representing the whole concept right? I can write your code for any Monte Carlo simulation and follow the same logic with x and y?
@philparisi_
@philparisi_ Жыл бұрын
Hi there, you are correct! You can easily chsnge the function (equation) I am using to due monte carlo on a different graph. Keep an eye out if your function goes below zero as I don’t think I generalized the code to consider that. You could also extend this to 3D, and instead of considering if a random pt is above a line, you check if the pt is above a surface z = f(x,y).
@Farzamkhv
@Farzamkhv Жыл бұрын
@@philparisi_ So, it can be done for energy simulation? for instance, changing the thickness of the walls and also glass type?
@philparisi_
@philparisi_ Жыл бұрын
@@Farzamkhv while I have not performed an energy simulation, YES. What I showed here is Monte Carlo ‘Integration’, and there are many other monte carlo methods that use randomness in an attempt to simulate certain scenarios
Monte Carlo Integration In Python For Noobs
15:32
Andrew Dotson
Рет қаралды 151 М.
Monte Carlo Simulation
10:06
MarbleScience
Рет қаралды 1,4 МЛН
Cute kitty gadgets 💛
00:24
TheSoul Music Family
Рет қаралды 17 МЛН
Чёрная ДЫРА 🕳️ | WICSUR #shorts
00:49
Бискас
Рет қаралды 6 МЛН
Happy birthday to you by Tsuriki Show
00:12
Tsuriki Show
Рет қаралды 12 МЛН
Applied Optimization - Monte Carlo Method
16:31
purdueMET
Рет қаралды 13 М.
Fourier Transforms FFT in MATLAB | MATLAB Tutorial
24:03
Phil Parisi
Рет қаралды 34 М.
Everything You Need to Know About Control Theory
16:08
MATLAB
Рет қаралды 538 М.
The Monte Carlo Method
16:01
RandomMathsInc
Рет қаралды 81 М.
6. Monte Carlo Simulation
50:05
MIT OpenCourseWare
Рет қаралды 2 МЛН
Cute kitty gadgets 💛
00:24
TheSoul Music Family
Рет қаралды 17 МЛН