MATLAB: How to write half rectified sine wave equation into Matlab format

half rectified sine wave

I am new to Matlab and having trouble writing this equation in a form that I could pass to a function as the argument f.
The function is:
function [A,B,C,F]=Fourierseries(f,t,n,a,b)
% Function description.
if nargin==3
a=-pi;
b=pi;
end
L=(b-a)/2;
A=zeros(1,n+1);
A(1)=int(f,t,a,b)/L;
B=zeros(1,n);
C=zeros(1,n+1);
F=A(1)/2;
C(1)=A(1)/2;
for k=1:n
ak=int(f*cos(k*pi*t/L),t,a,b)/L;
bk=int(f*sin(k*pi*t/L),t,a,b)/L;
ck=(ak-1i*bk)/2;
A(k+1)=ak;
B(k)=bk;
C(k+1)=ck;
F=F+ak*cos(k*pi*t/L)+bk*sin(k*pi*t/L);
end
end

Best Answer

This works:
f = @(t) sin(t).*(sin(t)>=0) + 0*(sin(t)<0); % Half-Wave Rectified Sine Function
t = linspace(0, 4*pi);
figure(1)
plot(t, f(t))
grid
axis([0 4*pi -1.5 1.5])
To pass the value of the ‘f’ function to your ‘Fourierseries’ function, since you are not evaluating it within the function, evaluate it first, and pass that to your function:
ft = f(t);
[A,B,C,F]=Fourierseries(ft,t,n,a,b);
That should work.