I am new to matlab. All i wanted was to integrate f(t)*cos(pi*n*t) over t through quadgk inside a loop where n varies from 1 to 10. But I guess the problem is that quadgk needs a function where only t is a variable and not n. how to do it???
t=linspace(0,12,1000);
T=2;
Y=g(t)';
rep=(t(end)-t([1]))/T;
f=0;
N=5;
hold on;
h=zeros(N,1);
clr=lines(N);
for n=1:2:N;
line(t,Y,'linewidth',5)
grid on;hold on;
A=(1/T)*quadgk(@g,0,T);
P=Y.*(cos(n*pi*t))';
Q=Y.*(sin(n*pi*t))';
Ax=(2/T)*quadgk(@s,0,T);
Bx=(2/T)*trapz(t,Q)/rep;
f=f+(Ax*cos(pi*n*t)+Bx*sin(pi*n*t));
final=A+f;
h(n)=plot(t,final,'linewidth',2,'Color',clr(n,:));
end
hold off;
legend(h, num2str((1:N)','harmonic-%d'))
function f=g(x)
z=2*floor(x/2);
x1=x-z;
y1=(1).*(0<=x1 & x1<=0.8);
y2=(-1).*(0.8<x1 & x1<2);
f=y1+y2;

 採用された回答

Matz Johansson Bergström
Matz Johansson Bergström 2014 年 8 月 24 日
編集済み: Matz Johansson Bergström 2014 年 8 月 24 日

0 投票

To solve this problem you can use a anonymous function handle to a function with x and n as arguments.
f = @(x) myfun(x, n);
So you define your function with 'function myfun(x,n)' and pass the handle f to quadgk like
quadgk(f,0,T)
Please note that I don't use @ here.

6 件のコメント

Nabhdeep Bansal
Nabhdeep Bansal 2014 年 8 月 24 日
function f=g(x)
z=2*floor(x/2);
x1=x-z;
y1=(1).*(0<=x1 & x1<=0.8);
y2=(-1).*(0.8<x1 & x1<2);
f=y1+y2;
t=linspace(0,12,1000);
T=2;
Y=g(t)';
f=0;
N=50;
hold on;
h=zeros(N,1);
clr=lines(N);
for n=1:25:N;
line(t,Y,'linewidth',5)
grid on;hold on;
A=(1/T)*quadgk(@g,0,T);
P=@(t)g(t).*(cos(n*pi*t));
Q=@(t)g(t).*(sin(n*pi*t));
Ax=(2/T)*quadgk(P,0,T);
Bx=(2/T)*quadgk(Q,0,T);
f=f+(Ax*cos(pi*n*t)+Bx*sin(pi*n*t));
final=A+f;
h(n)=plot(t,final,'linewidth',2,'Color',clr(n,:));
end
hold off;
legend(h, num2str((1:N)','harmonic-%d'))
Thank You Sir. It worked and I think the plots are correct.
Please check once and correct me if needed. Thank You once again. :)
Matz Johansson Bergström
Matz Johansson Bergström 2014 年 8 月 24 日
This is not the final code, right?
Nabhdeep Bansal
Nabhdeep Bansal 2014 年 8 月 24 日
This is the final code, Sir. What happened?
Matz Johansson Bergström
Matz Johansson Bergström 2014 年 8 月 24 日
Your code works, but I thought you wanted to pass n as an extra argument to the function, which is nicer, but if you are happy it's ok with me ;-)
Nabhdeep Bansal
Nabhdeep Bansal 2014 年 8 月 24 日
What you are saying is true Sir. The output curves are incorrect. How to pass n as an extra argument?
Matz Johansson Bergström
Matz Johansson Bergström 2014 年 8 月 24 日
You want to calculate the quadrature of f(t)*cos(pi*n*t), how do you define f?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by