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!