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!
0 个评论
采纳的回答
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 个评论
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 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!