MATLAB Answers

How to do integral for data

5 views (last 30 days)
Zhaokai Yin
Zhaokai Yin on 7 Jan 2021
Commented: Zhaokai Yin on 8 Jan 2021
How can I find y, if I know dy/dx from 0 to 1 ?
Since we know the integral of sinx is -cosx, I trie to use cumtrapz, but I cannot get correct line.
Here are my code. Can I have any hints for this? Thank you.
clear all;close all;clc
dt=0.1;
x=0:dt:2*pi;
y1=sin(x);
y2=-cos(x);
figure
subplot(211)
plot(x,y1,x,y2);grid on
legend('sinx','interal : -cosx')
dy1=cumtrapz(x,y1);
subplot(212)
plot(x,y1);hold on
plot(x,dy1);grid on
title('using cumtrapz')

Answers (1)

William
William on 7 Jan 2021
I have two comments:
  1. A more correct statement about the integral is that the integral of sin(x) is equal to C-cos(x), where C is a constant of integration. So, the most you can hope for is that your result is different from -cos(x) by a constant amount.
  2. Your program is comparing dy1 to y1. It should be comparing dy1 to y2. In that case, you will find that the graphs are the same, except for a constant displacement.
  1 Comment
Zhaokai Yin
Zhaokai Yin on 8 Jan 2021
Thanks for replying. I understand what you said. The integral of sinx is -cosx+C.
The shape of the red curve in the lower plot is correct,but the starting point of red curve should be -1.
So how I can find constant C properly? I think I already limit x range from 0 to 2pi.
Also if I change the x range to pi/2 to 2*pi, everything looks perfect. Somehow there will be a jump point close to 0. I don't know how to avoid it and to find correct vertical displacenment. Its really confusing.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by