JulianAngussmith
JulianAngussmith

Reputation: 75

Writing a MATLAB function for sinc(x)=sin(x)/x

I am trying to write a MATLAB function to evaluate sinc(x)=sin(x)/x over the interval [0,pi]. I have included my code below. It is saved as the file sinc3.m.

function y = sinc3(x)
if x<0
   disp('Outside specified interval of x');
   y=0;
elseif ((x>=0) && (x<=pi))
    sinc=@(x) sin(x)/x;
    y=sinc(x);
else
    disp('Outside specified interval of x');
   y=0;
end 
end 

The error message "sinc3 requires more input arguments to run" is displayed. I do not understand what this means.

Upvotes: 0

Views: 1975

Answers (1)

MichaelTr7
MichaelTr7

Reputation: 4767

Sinc Function for a Single Scalar:

Some adjustments for the function to run for a scalar input include setting the output y to zeros for the trivial cases that are outside the interval. This has to be done since the function is expected the output to be initialized and returned. Also, the if-statement do not require semi-colons in MATLAB at the end of them.

disp(sinc3(2));

function y = sinc3(x)
if x < 0
   disp('Outside specified interval of x');
  y = 0;

elseif ((x>=0) && (x<=pi))
    sinc= @(x) sin(x)/x;
    y =sinc(x);
    
else
   disp('Outside specified interval of x');
   y = 0;
   
end 
end

Using MATLAB's vectorized operations can greatly reduce the necessity of writing intricate loops. Below are two examples of evaluating and plotting a truncated sinc signal.

Plotting Sinc Symbolically/Anonymous Functions:

This method uses a logical array named Range to truncate the sinc and constrain the signal within the range [0,π]. Range will only be true "1" where the parameter x is greater than 0 and less than π. Everywhere else Range is false "0". By element-wise multiplying the sin(x)./x the sinc by Range the signal is truncated. This process can be visualized as multiplying a rectangular pulse that's only positive and exists within the range by the sinc.

Symbolically Evaluating Function

%Plotting the sinc symbolically%
syms x
Range = ((x >= 0) & (x <= pi));
sinc = @(x) (sin(x)./x).*Range;
fplot(sinc(x));

For Evaluating Specific Values/Vectors:

To evaluate specific values we can neglect declaring x as a symbolic variable and instead pass a vector as input into the anonymous function.

Anonymous Function With Vector Inputs

%Generating a vector of x-values to evaluate the sinc for%
Start_Time = 0; End_Time = 20;
Interval = 0.1;
X = (0:Interval:20);

Sinc_Signal = @(x) (sin(x)./x).*((x >= 0) & (x <= pi));
plot(X,Sinc_Signal(X),'Marker','.');
xlim([-5 5]);

Upvotes: 1

Related Questions