필터 지우기
필터 지우기

How to vectorize an integral?

조회 수: 6 (최근 30일)
Digvijay Rawat
Digvijay Rawat 2016년 5월 28일
댓글: Star Strider 2016년 5월 28일
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