ycliper

Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
Скачать

How to Perform Monte Carlo Integration in MATLAB | MATLAB Tutorial

Автор: Phil Parisi

Загружено: 2022-01-17

Просмотров: 18075

Описание: How to do a Monte Carlo Integral in MATLAB! Covers the theory behind the numerical method and integration while presenting a program to execute montecarlo integration in MATLAB!

🤝 Support me on Patreon!   / philparisi_  
🌱 Want to say thanks? https://buymeacoffee.com/philparisi_
🌏 More on Insta!   / philparisi_  
🔥 And the rest! https://linktr.ee/philparisi_

LEARN MATLAB
55-video MATLAB programming certification! https://trainings.internshala.com/mat...
2hr Complete Beginner Basics in MATLAB:    • Complete MATLAB Beginner Basics Course wit...  
MATLAB Formula Cheat Sheet: https://philparisi.weebly.com/code.html

CHAPTERS
0:00 Goal
0:07 Monte Carlo Theory
3:11 Setting up Code
5:24 Generate and Assign Points
9:35 Clean the Output
11:51 Plotting the Solution
12:26 Integral Calculation
13:18 MATLAB's integral()
13:51 Percent Error
14:25 Applying Script to Other Integrals

YOU DIG NUMERICAL INTEGRATION? Check out other advanced topics...
Indefinite and Finite Integrals    • Definite and Indefinite Integrals in MATLA...  
Fourier Transform    • Fourier Transforms FFT in MATLAB | MATLAB ...  
Analytical vs. Numerical Solutions    • Analytical vs Numerical Solutions Explaine...  
Dice Roll Simulation    • Dice Roll Simulation in MATLAB | MATLAB Tu...  
Convolution    • How to Perform a Convolution in MATLAB | M...  
Make a .MP4 From a Plot    • How to Make MP4 Video File from a Figure i...  

--------------------------FREE CODE FROM VIDEO ------------------------------------------------------------------------------------
% MonteCarlo - Integral Calculation
clc, clearvars, close all, format compact

% Equation to integrate over. Integral of this from a to b.
f = @(x) exp(x).*x.^2.*sqrt(exp(x));

% Parameters
N = 10000; % number of points to generate randomly
a = 2; % integral lower x limit - manual
b = 4; % integral upper x limit - manual
M = 1.4*max(f(linspace(a,b))); % upper y bound = c*max y_value from equation

% Generate Dots
for i = 1:N

% generate random pt
x_val = rand(1)*(b-a) + a;
y_val = rand(1)*M;

% compare random against the curve
fx = f(x_val);

% logic statement
if y_val REPLACE_WITH_LESS_THAN_SYMBOL fx % under the curve - blue
under(i,1) = x_val;
under(i,2) = y_val;
else % above the curve - red
above(i,1) = x_val;
above(i,2) = y_val;
end
end

% Filter out zeros
under2(:,1) = nonzeros(under(:,1));
under2(:,2) = nonzeros(under(:,2));
above2(:,1) = nonzeros(above(:,1));
above2(:,2) = nonzeros(above(:,2));

% Plotting
plot(above2(:,1),above2(:,2),'ro','MarkerFaceColor','r')
hold on
plot(under2(:,1),under2(:,2),'bo','MarkerFaceColor','b')
title('Monte Carlo Integration'), xlabel('x'), ylabel('y')
legend('above','under')

% Integral Calcs
MonteCarlo_Integral = length(under2) / N * (M*(b-a))
MATLAB_Integral = integral(f,a,b)
PercentError = abs(MATLAB_Integral - MonteCarlo_Integral)/MATLAB_Integral * 100


-------------------------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,'.')
----------------------------------------------------------------------------------------------------------------------

HELP A BROTHER OUT
Thank you so much for watching! Please consider subscribing as a thank you if you benefited from this content! :D

HELPING MY BROTHERS AND SISTERS OUT
Comment below and I will happily answer all your questions, queries, and conundrums... whether or not they pertain to programming ;)

🤝 Support me on Patreon!   / philparisi_  
🌱 Want to say thanks? https://buymeacoffee.com/philparisi_
🌏 More on Insta!   / philparisi_  
🔥 And the rest! https://linktr.ee/philparisi_

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
How to Perform Monte Carlo Integration in MATLAB | MATLAB Tutorial

Поделиться в:

Доступные форматы для скачивания:

Скачать видео

  • Информация по загрузке:

Скачать аудио

Похожие видео

How to Load, Clean, and Visualize Raw CSV Data in MATLAB | MATLAB Tutorial

How to Load, Clean, and Visualize Raw CSV Data in MATLAB | MATLAB Tutorial

6. Monte Carlo Simulation

6. Monte Carlo Simulation

Monte Carlo Integration In Python For Noobs

Monte Carlo Integration In Python For Noobs

Моделирование Монте-Карло

Моделирование Монте-Карло

19 лучших функций в MATLAB | Учебное пособие по MATLAB

19 лучших функций в MATLAB | Учебное пособие по MATLAB

Monte Carlo Simulation of a Stock Portfolio with Python

Monte Carlo Simulation of a Stock Portfolio with Python

The Monte Carlo Method

The Monte Carlo Method

Простое решение для действительно сложных проблем: моделирование методом Монте-Карло

Простое решение для действительно сложных проблем: моделирование методом Монте-Карло

Все, что вам нужно знать о теории управления

Все, что вам нужно знать о теории управления

⚡️ Удар по скоплению силовиков || Жуткий теракт в центре Львова

⚡️ Удар по скоплению силовиков || Жуткий теракт в центре Львова

Fourier Transforms FFT in MATLAB | MATLAB Tutorial

Fourier Transforms FFT in MATLAB | MATLAB Tutorial

Мощнейший удар по флоту и авиации РФ / Улицы столицы перекрыты

Мощнейший удар по флоту и авиации РФ / Улицы столицы перекрыты

Учебное пособие по MATLAB Simulink для начинающих (шаг за шагом!)

Учебное пособие по MATLAB Simulink для начинающих (шаг за шагом!)

4 Hours Chopin for Studying, Concentration & Relaxation

4 Hours Chopin for Studying, Concentration & Relaxation

OpenClaw: чит-код для продуктивности или подарок хакерам?

OpenClaw: чит-код для продуктивности или подарок хакерам?

Микросервисы VS Монолит | Просто о сложном

Микросервисы VS Монолит | Просто о сложном

Taylor series | Chapter 11, Essence of calculus

Taylor series | Chapter 11, Essence of calculus

Создание пользовательских функций в MATLAB: синтаксис и примеры

Создание пользовательских функций в MATLAB: синтаксис и примеры

What is Monte Carlo Simulation?

What is Monte Carlo Simulation?

MATLAB Nonlinear Optimization with fmincon

MATLAB Nonlinear Optimization with fmincon

© 2025 ycliper. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]