How to vectorize an integral?

2 次查看(过去 30 天)
function exdpo7_11 % script is function to allow for subfunctions
clc, close all;
clear
ans = 0;
n = -5:0.1:6;
int = integral(@fdpo7,-5,6);
disp(['integral = ',num2str(int)]);
fplot(@fdpo7,[-5 6]);
for i = 1:1:(length(n)-1)
int = integral(@fdpo7,n(i),n(i+1));
ans = ans+int;
end
ans
function y = fdpo7(x)
if x < -1
y = exp(x+1);
elseif x < 5
y = 2 + cos(pi*x);
else
y = 2*(x-5) + 1;
end
Hi!
In the above piece of code, I have to calculate the integral of the function given in the subfunction 'fdpo7' using vectorization. I have already calculated the integral using a for loop as you can see but I am unable to think as to how to integrate the function by vectorising the code and not using the for loop. Any help will be appreciated.
Thanks!

采纳的回答

Star Strider
Star Strider 2016-5-28
编辑:Star Strider 2016-5-28
This will likely work:
fdpo7 = @(x) exp(x+1).*(x < -1) + (2 + cos(pi*x)).*((x < 5) & (x >= -1)) + (2*(x-5) + 1).*(x >= 5);
x = linspace(-10, 10); % Test & Plot
figure(1)
plot(x, fdpo7(x))
grid
The ‘Test & Plot’ section is not necessary for the code. I just shows that the ‘y’ function does what you want it to.
EDIT I originally named the function ‘y’, corrected it to be ‘fdpo7’.
  2 个评论
Digvijay Rawat
Digvijay Rawat 2016-5-28
Worked! Thanks a lot for your help :)
PS : The edit was not necessary, I am not that new to MATLAB :P
Star Strider
Star Strider 2016-5-28
My pleasure!
Your code appears to be sophisticated, but I wanted to remove any ambiguity. It’s always best to provide seamless code, as you will discover when you join the happy throng here providing Answers, and start guiding others. Please share your expertise here when you have the time.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by