Matlab Integral function for a self teaching beginner
14 views (last 30 days)
Show older comments
Bruce Griffin
on 14 Jul 2022
Answered: Steven Lord
on 14 Jul 2022
I need to take an integral over a meshgrid of space and time.
at each point in space and time I need to take an integral and Im having trouble understand the integral command.
To simplify I need where t is time an x is space and c is what im integrading over.
I believe that
t=0:1:10
x=0:1:10
[time space]=meshgrid(t,x)
fun=@(c) time+space+c
answer=integral(fun,-10,10)
So why does this not work but
answer=integral(fun,-10,10,'ArrayValued',1) does?
Im trying to conceptualy understand
0 Comments
Accepted Answer
Star Strider
on 14 Jul 2022
The integral function numerically integrates the function supplied to it over the variable range defined in the function call. It does not assume matrix data unless you tell it, otherwise assuming scalar data.
t=0:1:10;
x=0:1:10;
c = pi; % Create 'c'
[time space]=meshgrid(t,x);
fun=@(c) time+space+c;
answer_cols=trapz(fun(c))
answer = trapz(answer_cols)
.
3 Comments
Star Strider
on 14 Jul 2022
Use the integral function with the 'ArrayValued' name-value pair.
The integral function and the trapz (or incremental cumtrapz) functions do different things depending on what the data are and what result you want.
More Answers (1)
Steven Lord
on 14 Jul 2022
By default, integral calls the integrand function you pass into it with an array of data, not just a scalar. It requires your integrand function to return an array the same size as the input as output. Each element of the output represnts the value of your integrand function at the corresponding element of the input.
In your code:
t=0:1:10;
x=0:1:10;
[time space]=meshgrid(t,x);
fun=@(c) time+space+c;
that would only work if c was compatibly sized with time and space. One example of a c that's compatibly sized is a scalar.
fun(42)
One example of a c that's not compatibly sized with time and space is a 1-by-2 vector. Adding an 11-by-11 matrix and a 1-by-2 matrix is not mathematically defined.
fun([42, -1])
But you have no control over the size of the data with which integral calls your function, unless you explicitly tell it "My function returns an array of data, so just call it with a scalar each time". That's what the 'ArrayValued' name-value argument tells integral if you specify that the value of that name-value argument as 1.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!