diff --git a/contents/monte_carlo_integration/code/matlab/monte.m b/contents/monte_carlo_integration/code/matlab/monte.m new file mode 100644 index 000000000..dc0ee8092 --- /dev/null +++ b/contents/monte_carlo_integration/code/matlab/monte.m @@ -0,0 +1,21 @@ +pi_estimate = monte_carlo(10000000); + +fprintf("The pi estimate is: %f\n", pi_estimate); +fprintf("Percent error is: %f%%\n", 100 * abs(pi_estimate - pi) / pi); + +function pi_estimate=monte_carlo(n) + + % a 2 by n array, rows are xs and ys + xy_array = rand(2, n); + + % square every element in the array + squares_array = xy_array.^2; + + % sum the xs and ys and check if it's in the quarter circle + incircle_array = sum(squares_array)<1; + + % determine the average number of points in the circle + pi_estimate = 4*sum(incircle_array)/n; + +end + diff --git a/contents/monte_carlo_integration/monte_carlo_integration.md b/contents/monte_carlo_integration/monte_carlo_integration.md index 645fc2315..b6bb2b343 100644 --- a/contents/monte_carlo_integration/monte_carlo_integration.md +++ b/contents/monte_carlo_integration/monte_carlo_integration.md @@ -91,6 +91,8 @@ each point is tested to see whether it's in the circle or not: [import:2-10, lang:"bash"](code/bash/monte_carlo.bash) {% sample lang="kotlin" %} [import:3-3, lang:"kotlin"](code/kotlin/MonteCarlo.kt) +{% sample lang="m" %} +[import:8-15, lang:"matlab"](code/matlab/monte.m) {% sample lang="scratch" %}

@@ -193,6 +195,8 @@ Feel free to submit your version via pull request, and thanks for reading! [import, lang:"bash"](code/bash/monte_carlo.bash) {% sample lang="kotlin" %} [import, lang:"kotlin"](code/kotlin/MonteCarlo.kt) +{% sample lang="m" %} +[import, lang:"matlab"](code/matlab/monte.m) {% sample lang="scratch" %} The code snippets were taken from this [scratch project](https://scratch.mit.edu/projects/319610349)