Wednesday 4 February 2009

How to make our own functions?

In the previous post I've given a simple example to capture and analyze sound. In it I've used a function daqdocfft which is not a built in one. I got it from Mathworks. Similar to it we can create our own functions for peculiar applications. The function daqdocfft is given below


%================Program====================%

function [f,mag] = daqdocfft(data,Fs,blocksize)
% [F,MAG]=DAQDOCFFT(X,FS,BLOCKSIZE) calculates the FFT of X
% using sampling frequency FS and the SamplesPerTrigger
% provided in BLOCKSIZE

xfft = abs(fft(data));

% Avoid taking the log of 0.
index = find(xfft == 0);
xfft(index) = 1e-17;

mag = 20*log10(xfft);
mag = mag(1:floor(blocksize/2));
f = (0:length(mag)-1)*Fs/blocksize;
f = f(:);



%============Program Ends=======%

function is a built in key word. It should be given in the start to make a function. It is then followed by the return values. Then comes the original name of the new function followed by its arguments. The function name with its arguments is equated to function return_value.
After writing this you can write the code for what the function should do actually.

querrymail@gmail.com