Octave specgram generates two diffent answers - octave

I have a project where I have to recognize the frequency from an audio file. For this I use a single tone of 10 kHz to see if I can get it working.
Since I am pretty new to Octave, I tried this example with my own audio file.
I tried to understand what happens by doing some research to all functions.
My question here is; if I let specgram plot the figure when I do not specify it's output:
specgram(y,fftn,Fs,hanning(window),step);
it gives a line at 10kHz which is what I want.
But if I specify the output for the specgram function
[S,f,t]= specgram(y,fftn,Fs,hanning(window),step);
and let it plot, it plots the line at 18 kHz.
I figured it have to be in the inputs for the figure and I tried modifying these a bit, but every time I do that Octave gives an error.
I need the frequency as an given output, since I have to do some calculations with it, I figured I need to specify the frequency output.
This is the part of the code that specify the plot for the spectrogram:
step= fix(5*Fs/1000); % stepsize of the window
window= fix(90*Fs/1000); % window size
fftn =2^nextpow2(window); % Size of the FFT block
[S,f,t]= specgram(y,fftn,Fs,hanning(window),step);
S= abs(S(2:fftn*12000/Fs,:)); % Normalize the phase
S= S/max(S(:)); % Normalize the Energy
S= max(S, 10^(-40/10)); % Throw out values below -40 dB and above -3dB
S= min(S, 10^(-3/10));
figure
imagesc(t,f,(log(S)));
Can anyone help me here how to gain the frequency data from the audio file so I can use it in some calculations?
I have searched for answers already in the Octave manual for help and I tried it with various matlab sites. Also checked already many posts here such as:
How does Octave spectrogram 'specgram' from signal work?
Methodology of FFT for Matlab spectrogram / short time Fourier transform functions
P.S. Sorry for my bad English, it's not my native language

I found the answer myself, it turns out it is in this line of code:
S= abs(S(2:fftn*12000/Fs,:));
if I delete this line, the lines are placed on the right frequency in the figure. To me it looks like this line just takes a small space of the fft and replaces it with other frequencies but I'm not shure about that.

Related

Amplitude Spectrum of a function

My question is related to plotting amplitude spectrum.
Problem 1: (I have solved it) I have to represent the following function as a discrete set of N=100 numbers separated by time increment of 1/N:
e(t) = 3sin2.1t + 2sin1.9t
I did it using stem function in matlab and plotted it.
Problem 2: (I have question about it) The next thing was to repeat the same above all, using dataset of 200 points with time increment of 1/N and 1/2N.
My question is a bit basic but I just want to clear if I am following the right path to solve my problem.
I want to ask that for problem 2, for both 1/N and 1/2N, should I use N=200 (as I believe it is separate problem)?
A few of my mates have suggested using N=100 for 1/N and N=200 for 1/2N.
which one is the right thing?
Any help will be highly appreciated. Thanks

fft: fitting binned data

I want to fit a curve to data obtained from an FFT. While working on this, I remembered that an FFT gives binned data, and therefore I wondered if I should treat this differently with curve-fitting.
If the bins are narrow compared to the structure, I think it should not be necessary to treat the data differently, but for me that is not the case.
I expect the right way to fit binned data is by minimizing not the difference between values of the bin and fit, but between bin area and the area beneath the fitted curve, for each bin, such that the energy in each bin matches the energy in the range of the bin as signified by the curve.
So my question is: am I thinking correctly about this? If not, how should I go about it?
Also, when looking around for information about this subject, I encountered the "Maximum log likelihood" for example, but did not find enough information about it to understand if and how it applied to my situation.
PS: I have no clue if this is the right site for this question, please let me know if there is a better place.
For an unwindowed FFT, the correct interpolation between bins is by using a Sinc (sin(x)/x) or periodic Sinc (Dirichlet) interpolation kernel. For an FFT of samples of a band-limited signal, thus will reconstruct the continuous spectrum.
A very simple and effective way of interpolating the spectrum (from an FFT) is to use zero-padding. It works both with and without windowing prior to the FFT.
Take your input vector of length N and extend it to length M*N, where M is an integer
Set all values beyond the original N values to zeros
Perform an FFT of length (N*M)
Calculate the magnitude of the ouput bins
What you get is the interpolated spectrum.
Best regards,
Jens
This can be done by using maximum log likelihood estimation. This is a method that finds the set of parameters that is most likely to have yielded the measured data - the technique originates in statistics.
I have finally found an understandable source for how to apply this to binned data. Sadly I cannot enter formulas here, so I refer to that source for a full explanation: slide 4 of this slide show.
EDIT:
For noisier signals this method did not seem to work very well. A method that was a bit more robust is a least squares fit, where the difference between the area is minimized, as suggested in the question.
I have not found any literature to defend this method, but it is similar to what happens in the maximum log likelihood estimation, and yields very similar results for noiseless test cases.

Face coloring in Matlab revisited

Using Mathematica I was able to create the following plot
Now I would like to switch to Matlab - which I am just starting to learn. I was able to create the triangulation with FL.vertices and FL.faces matrix and the patch function, that looks like this
faces=FV.faces;
facecolor = [.7 .7 .7];
patch('faces',faces,'vertices',FV.vertices,...
'facecolor',facecolor,'facealpha',0.8,'edgecolor',[.8.8.8]);
camlight('headlight','infinite');
daspect([1 1 1]); axis vis3d; axis off
material dull;
It produces a dull image:
Now, I have a function J that takes the matrix FL.vertices and returns a matrix of positive values. I would like to color the faces according to the values of J on vertices. Possibly interpolate along the faces. Edges can be, for now, as they are - to deal with later. After reading the documentation it is not clear to me how to accomplish this task. Do I need to find min and max of J manually? Or can Matlab do it automatically? It is OK for now to use one of Matlab's preset coloring schemes, something like a "temperature map" would do. At which point should I call my function J? How exactly it should be used with the patch command? I looked through the previous answers to a similar question, but still I am not able to figure out how to deal with my case. Any helping suggestion will be appreciated.
P.S.
OK. I think I did it with simple
FV.Cdata=sphere_jacobian(FV.vertices,1,1,0,1);
figure
Hp = patch('faces',FV.faces,'vertices',FV.vertices,...
'FaceVertexCData',FV.Cdata,'facecolor','interp','edgecolor',[.8 .8 .8]);
But I am not sure if min and max have been automatically computed and interpolated.
Here is what I believe to be the answer given by the poster, I will put it here so the question does not remain open.
OK. I think I did it with simple
FV.Cdata=sphere_jacobian(FV.vertices,1,1,0,1);
figure
Hp = patch('faces',FV.faces,'vertices',FV.vertices,...
'FaceVertexCData',FV.Cdata,'facecolor','interp','edgecolor',[.8 .8 .8]);
But I am not sure if min and max have been automatically computed and interpolated.
I did
colormap(hsv(3200));
and normalized my function:
jac = sphere_jacobian(FV.vertices,m);
minj = min(jac);
maxj = max(jac);
jac1 = (jac-minj*ones(size(jac)))/(maxj-minj);FV.Cdata=jac1;
figure Hp = patch('faces',FV.faces,'vertices',FV.vertices,... 'FaceVertexCData',FV.Cdata,'facecolor','interp','edgecolor',[.8 .8 .8]);
The result can be seen here.

octave runs ok but plot is not displayed?

HI there
I am using Octave 2.3.4 with a plot command. I am new at Octave. This plot does not display for some reason. Here is my M file sample:
1;
clear all;
%%%%%%%%% parameters setting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
r=0.01; %risk free rate
S0=50; %underlying price 1
%create an implied volatiltiy surface using below parameters:
basevol=0.25; %implied volatility at time t=0 and in center of strike axis
skewT=-0.001; %icrease in vol for one unit increase in maturity
v1=0.1; %defines how much a smile is raised at left end from base vol
v3=0.2; %defines how much a smile is raised at right end from base vol
nK=100; %no. of strike steps
nT=10; %no. of time steps
Tmax=1; %maximum value in time axis
Kmin=1; %minimum value in strike price axis
Kmax=150; %maximum value of strike price axis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dt=Tmax/(nT-1);
Tvec=0:dt:1;
dk=(Kmax-Kmin)/(nK-1);
Kvec=Kmin:dk:Kmax;
Tvec=Tvec';
Kvec=Kvec';
nK=size(Kvec,1);
nT=size(Tvec,1);
dvolT=ones(nK,nT)*(skewT*dt);
dvolT=cumsum(dvolT,2);
SmileVec=GetSmile(Kvec,v1,0,v3);
dvolK=ones(nK,nT);
dvolK=repmat(SmileVec,1,nT);
ImpliedVolSurface=ones(nK,nT)*basevol+dvolT+dvolK;
%use formula mentioned by John Elder in "Hedging for Financial Derivatives"
%this formula gives local volatility using implied volatility
function ret=GetLocalVolSurface(ImpliedVolSurface, S, r, Kvec, Tvec)
[m,n]=size(ImpliedVolSurface);
LocalVolSurface=zeros(m,n);
dk=Kvec(2)-Kvec(1);
dt=Tvec(2)-Tvec(1);
x=ImpliedVolSurface;
for i=3:m-2, %loop over strikes
for j=1:n-1, %loop over time steps
dv_dk=(x(i+1,j)-x(i-1,j))/(2*dk);
dv2_dk2=(x(i-1,j)-2*x(i,j)+x(i+1,j))/(dk*dk);
dv_dt=(x(i,j+1)-x(i,j))/dt;
K=Kvec(i);
T=Tvec(j+1);
rT=T^0.5;
sig=x(i,j);
h1=(log(S/K)+r*T+0.5*sig*sig*T)/(sig*rT);
numer=sig*sig + 2*T*sig*dv_dt + 2*r*K*T*sig*dv_dk;
denom=(1+K*h1*rT*dv_dk)^2 + K*K*T*sig*sig*(dv2_dk2-h1*dv_dk*dv_dk*rT);
LocalVolSurface(i,j)=(numer/denom)^0.5;
end
end
ret=LocalVolSurface;
endfunction
LocalVol_Surface=GetLocalVolSurface(ImpliedVolSurface,S0,r,Kvec,Tvec);
AsyImplVols=zeros(nK,1);
T=Tvec(nT-1);
F=S0*exp(r*T);
for i=3:nK-2,
% use formula sigBS(F,K)=sigLoc( (F+K)/2 )
K=Kvec(i);
lookupK=(F+K)/2;
kdiff=abs(Kvec-lookupK); %try to find nearest point in grid
kidx=min(find(kdiff==min(kdiff)));
if ( (kidx > 3) && (kidx < nK-2) ),
AsyImplVols(i)=LocalVol_Surface(kidx);
else
AsyImplVols(i) = NaN;
end
end
figure(1);
plot(Kvec(3:nK-2),[ImpliedVolSurface(3:nK-2,nT-1) LocalVol_Surface(3:nK-2,nT-1) AsyImplVols(3:nK-2)]);
When I run in Octave with no error, the plot is never displayed. It does include gnuplot 1.0.1 which I understand does the graph? Is there something I am not doing or missing? I am also running this on Windows 2003 Server.
Thanks
I got the answer here. Octave by default uses fltk for plotting etc, which is failing to work, using gnuplot works here. Just add below lines to .octaverc file in your home directory.
graphics_toolkit("gnuplot")
So that every time octave starts it will set the default package for plotting to gnuplot
I do know that's an old question but since I ran into quite the same error yesterday, maybe this can help someone else, too:
According to the Octave wiki pages, there seems to be a problem with plotting and the "oct2mat"-library. For me, the problem was solved after I ran this at the octave command prompt:
pkg rebuild -noauto oct2mat
and restarted octave. When you need to use "oct2mat", type:
pkg load oct2mat
Hope that helps!
I get the same problem installing on a windows 7 64 bit laptop (HP 630) with intel graphics. Every time you plot, it fails to do anything, but if you plot again, it shows up. It's some kind of refresh bug. It's annoying, but if you plot twice, the second time it works.
I am wondering if it is some kind of double buffering bug, because it works correctly on my own laptop running windows 7 with a dedicated graphics card.
In any case, try plotting twice in a row, I'll bet it works, and please let me know what the machine and video card are, because I've reported this to octave development.

2D non-polynomial function fitting from the command line

I just wrote a simple Unix command line utility that could be implemented a lot more efficiently. I can measure its performance by just running it on a number of inputs and measuring the time it takes. This will produce a set of pairs of numbers, s t, where s is the input size and t the processing time. In order to determine the performance characteristics of my utility, I need to fit a function through these data points. I can do this manually, but I prefer to be lazy and let a utility do it for me.
Does such a utility exist?
Its input is a sequence of pairs of numbers.
Its output is a formula that expresses how the second number depends as a function on the first, plus an error measure.
One step of the way is to have a utility that does this just for polynomials.
This has been discussed here but it didn't produce a ready-to-use solution.
The next step is to extend the utility to try non-polynomial terms: negative-degree polynomials (as in y = 1/x) and logarithmic terms (as in y = x log x) will need to be tried as well. One idea to cope with the non-polynomial terms is to just surround the polynomial fitting with x and y scale transformations. I don't know whether that will do. This question is related but not exactly the same.
As I said, I'm lazy: I'm not looking for ideas on how to to write this myself, I'm looking for a reliable result of a project that has already done it for me. Any suggestions?
I believe that SAS has this, RS/1 has this, I think that Mathematica has this, Execel and most spreadsheets have a primitive form of this and usually there are add-ons available for more advanced forms. There are lots of Lab analysis and Statistical analysis tools that have stuff like this.
RE., Command Line Tools:
SAS, RS/1 and Minitab were all command line tools 20 years ago when I used them. I bet at least one of them still has this capability.