Error using command integral
1 回表示 (過去 30 日間)
古いコメントを表示
Hi,
i have to valute this function
and plot the graphics for , i wrote:
u=linspace(0,4,1000);
q=integral(@(x)exp(-x.^2),0,u)-1/2;
and here i get:
'Error using integral (line 85)
A and B must be floating-point scalars.'
so i can't plot(u,q).. what can i do??
Thanks for the support and soryr for my bad english.
0 件のコメント
採用された回答
John D'Errico
2019 年 5 月 25 日
編集済み: John D'Errico
2019 年 5 月 25 日
Simplest is to just use cumtrapz. All you want is a plot anyway.
u = linspace(0,4,1000);
fun = @(x)exp(-x.^2);
plot(u,cumtrapz(u,fun(u)))
If all you want is the plot, then using a little bb-gun (cumtrapz) can be better than wielding a big gun like integral.
If you wanted to use integral, then you need to recognize that integral is not designed to solve a cumulative integral, so for an entire list of upper limits. You can't give it a vector of limits, and want it to work directly.
Simplest then could be to use a loop.
u = linspace(0,4,1000);
fun = @(x)exp(-x.^2);
uint = zeros(size(u));
for i = 2:numel(u)
uint(i) = integral(fun,u(i-1),u(i));
end
uint = cumsum(uint);
plot(u,uint)
As you can see, I only integrate each segment, then I formed the cumulative sum. This will be more efficient than integrating from 0 to u(i), each pass through the loop, since there is no need to re-integrate the early parts each time.
Finally, if you ABSOLUTELY, POSITIVELY, DESPERATELY need to do the integral in a vectorized form, you could do it, but why? Writing "elegantly" vectorized code will often result in less readable, code, that is hard to debug. Unless there is a reason for efficiency, the vectorized form may be of little real value. But, CAN you? Sigh. Yes.
u = linspace(0,4,1000);
fun = @(x)exp(-x.^2);
intfun = @(upplim) integral(fun,0,upplim);
uint = arrayfun(intfun,u);
plot(u,uint)
The simplest code (the first) is the most efficient code. It is readable. Not always quite as accurate, but by use of a sufficiently fine grid spacing, it will be quite adequate. And the spacing used here? 1000 steps, from 0-4? Trapzezoidal rule is entirely adequate for such a fine spacing.
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Object Containers についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!