MATLAB: Function to play sequential tones with frequencies as input arguments

soundtones

I am new to MATLAB and trying to write a function that produces multiple tones and plays them through the soundcard sequentially, with an interstimulus interval (ISI) between each tone. For input arguments, I want the function to accept the frequency of tones to be played (so tones(500,1000,1500) would play 3 tones at the three respective frequencies).
I am new, so don't judge, but thus far I have:
sequence=[];
for k=1:length(nargin)
if nargin==0;disp('Error! Please enter at least one frequency.');
elseif nargin>0;freq=varargin{1:length(nargin)};end;
sr=44100;
dur=0.5; %tone duration is 0.5 sec
t=0:1/sr:dur;
y=sin(2*pi*freq*t);
isiDur=1.5; %ISI duration is 1sec+tone duration because they play simultaneously
isiT=0:1/sr:isiDur; %ISI will now play for 1sec after tone
isi=sin(0*isiT);
sequence=[sequence;y(:)];
end;
sound(sequence,sr)
If I play sound(y,sr) sound(isi) then I can get one tone and ISI. But, I can't get sequential tones regardless of the ISI aspect. Please help!

Best Answer

Morgan - I'm guessing that the above code is the body of a function that has a variable number of inputs...that is why you are using nargin and varargin (your function may even be named tones?).
nargin indicates the number of input parameters/arguments to your function. Since it is an integer, it will be represented by a 1x1 scalar. So the
length(nargin)
will always be one, which isn't what you want. So you need to change your code slightly so that you are able to access each input parameter (and not just the first one)
function tones(varargin)
if nargin==0
error('Error! Please enter at least one frequency.');
end
sequence=[];
for k=1:nargin
freq=varargin{k};
sr=44100;
% etc.
end
The above isn't all that different from your code, it just does the nargin==0 check outside of the loop, and uses the error function if this is true. We then iterate over each input argument (frequency) and do as you did before. Try the above and see what happens!
Related Question