How do I properly setup numerical integration in MATLAB?
I'm looking to integrate this expression:
However I seem to be having problems setting up the function. As outlined in this MATLAB explanation, I've defined a separate function named 'NDfx.m' which looks like this:
function [ y ] = NDfx(x)
y = (1/sqrt(2*pi))*exp(-.5*x^2); % Error occurs here
end
However when I call it within my main function I get an error at the commented line above. My main function looks like this:
function[P] = NormalDistro(u,o2,x)
delta = x-u;
dev = abs((delta)/o2); % Normalizes the parameters entered into function
P_inner = quad(@NDfx,-dev,dev); % Integrates function NDfx from -dev to dev (error here)
P_outer = 1 - P_inner; % Calculation of outer bounds of the integral
if delta > 0
P = P_inner + (P_outer/2);
elseif delta < 0
P = P_outer/2;
elseif dev == 0
P = .5;
end
end
The specific error that I get is:
Error in ==> mpower
Inputs must be a scala开发者_如何转开发r and a square matrix
You've setup everything correctly for integration. The error is in the definition of the function itself. When using variables for function that will be integrated, a "." (period) must precede operators like ^
and *
when they are applied to the variable:
function [y] = NDfx(x)
y = (1/sqrt(2*pi))*exp(-.5*(x.^2));
end
Krono and user57368 are correct. They have already correctly answered your actual question. My answer is merely to answer the question you did not ask. That is, why are you using quad here at all? The point is that many people want to integrate a function of that form, and it has been done already! Use existing tools to solve your problems, as those tools will often have been written by someone who knows how to solve the problem accurately and efficiently.
In this case, the existing tool is comprised of the functions erf and erfc. They provide an accurate, efficient, vectorized solution to your problem. The only thing you will need to do is figure out how to transform those integrals to your current problem, done by a simple scaling of the input to erf and the output.
精彩评论