Anonymous Functions in Matlab

Anonymous Functions in Matlab

There is a way to create a one-line expression-based MATLAB function that does not require a program file. It is called an anonymous function. The following very simple example shows how it works.

%% EXAMPLE n.1
% square function

my_sqr = @(x) x.^2;
my_sqr(4) % returns 16

It is very useful when you want to calculate the values without storing them to a variable (vector, or matrix) while keeping the code simple (without creating another program file).

%% EXAMPLE n.2 
% Butterworth filter

% define the frequency axis
freq_axis = logspace(1,3,1000);

% define the function that calculates the FRF function (in dB)
% of a Butterworth filter
Butterworth_FRF = @(f,n,fc) 20*log10(1./(1+(f/fc).^n));

% plot the FRF for different orders n
fc = 100; % cut-off frequency of a Butterworth filter
for n = 1:5
    semilogx(freq_axis,Butterworth_FRF(freq_axis,n,100),'linewidth',2,'Displayname',['order = ' num2str(n)]);
    hold on
grid on
ylim([-50 0]);
xlabel('Frequency [Hz]');
ylabel('Gain [dB]');
Comments are closed.