Effacer les filtres
Effacer les filtres

How to vectorize an integral?

6 vues (au cours des 30 derniers jours)
Digvijay Rawat
Digvijay Rawat le 28 Mai 2016
Commenté : Star Strider le 28 Mai 2016
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!

Réponse acceptée

Star Strider
Star Strider le 28 Mai 2016
Modifié(e) : Star Strider le 28 Mai 2016
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 commentaires
Digvijay Rawat
Digvijay Rawat le 28 Mai 2016
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 le 28 Mai 2016
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by