matlabsignal-processing

How to Implement Box Function in better way in Matlab?

• This function in Matlab presents Box_Function:

• output = 1 while sample n belongs to the range (-a, +a).
• otherwise the output is 0 outside that range.
• So how can I implement this function in Matlab in a better way to shift the plot in case of negative values of time, without assigning negative values to the array.

``````function B_X = Box_Func(N,K,a)
if(N <= 0)||(K+a > N)
warning('Please Enter Valid Positive Integer !');
else
B_X = zeros([-N N]);
for i = -N : 1 : N
if (i >= K-a) && (i <= K+a)
B_X(i)=1;
end
end
end
end
``````

Solution

• ``````function B_X = Box_Func(N,K,a)
%   Box_Func This Function takes Number of Samples N,Count of shift K, and
%   half of Box width a then it stem Them ,
%   Note it works only for positive shifting
%   that means K should be positive or Zero

if(N <= 0)||(K+a > N) % if samples Number wrong, or shifting exceeds limit
% of Samples Print a warning.
warning('Please Enter Valid Positive Integer !');
else % if The inputs are fine , then :
B_X = zeros([1 2*N+1]);
x = -N:N;
B_X(x>=(K-a) & x<=(K+a)) = 1;
end
%===========================================
% Plotting the Results
%===========================================
figure('Name','Box Function','NumberTitle','off');
stem(x,B_X)
hold on
xlabel('Samples')
ylabel('Box Shifeted Function')
xlim([-N N]) ;
ylim([-1 2]);
grid on
hold off
end
``````