Calculating slope of a quasar spectrum for power law fitting - matlab

Working with Sloan Digital Sky Spectrum, I created a composite spectrum of quasars. The spectrum is a plot between wavelength (x-axis) measured in Angstrom and flux (y-axis) measured in ergs/cm^2/s/Angstrom.
For calculation of power law, I converted wavelength into frequency which resulted in THz scale frequency. On y-axis, I first changed the units from ergs/cm^2/s/Angstrom to ergs/cm^2/s/Hz by translating this to MATLAB and than to jansky units. This is the resultant plot.
Now I want to calculate slope of this graph, should I use the basic fitting tools and take the value of m from there? What are other methods to calculate slope for quasar spectrum for power law f = f_o nu^(-slope).

Use polyfit with degree 1 to fit a linear model.
P = polyfit(Xtrain, Ytrain, 1);
P will be a vector of two components:
The offset (or 0 degree component) and
The slope (or first degree component).
You can then fit new data (test data) by applying the fitted linear model
Ytest = P(1) * Xtest + P(2);

Related

Matlab question. What is this fft code doing?

I am new to Matlab and performing signal processing. I am trying to understand what this code is doing? How and why are we determining the indexNyquist and spectrum?
spectrum = fft(Signal,k); %generate spetrum of signal with FFT to k points
indexNyquist = round(k/2+1); %vicinity of nyquist frequency
spectrum = spectrum(1:indexNyquist); %truncate spectrum to Nyquist frequency
spectrum = spectrum/(length(Signal)); %scale spectrum by number of points
spectrum(2:end) = 2 * spectrum3(2:end); %compensate for truncating negative frequencies, but not DC component
For a purely real input signal the corresponding FFT will be complex conjugate symmetric about the Nyquist frequency, so there is no useful additional information in the top N/2 bins. We can therefore just take the bottom N/2 bins and multiply their magnitude by 2 to get a (complex) spectrum with no redundancy. This spectrum represents frequencies from 0 to Nyquist (and their aliased equivalent frequencies).
Note that bin 0 (0 Hz aka DC) is purely real and does not need to be doubled, hence the comment in your Matlab code.

How to filter 1D vector data using a cut-off wavelength in matlab?

I am trying to apply a high-pass filter to a signal (column or row vector) consisting of 1-pixel-wide lines taken from a black-and-white image. I know the resolution of the image (res in the code below, given in mm/pixel). How can I filter these line data in MATLAB to discard certain low frequencies (waviness) or large wavelengths, say >10 mm, using a Butterworth filter or any other?
Line data are not centered at zero.
Fs = 1; % I do not know if this assumption is correct for the image.
Fn = Fs/2; % Nyquist frequency.
lambda = 10; % Cut-off wavelength in mm, given.
samples_in_lambda = lambda/res; % divide by resolution to get samples.
fc = 1/samples_in_lambda; % Cut-off frequency from lambda.
I tried : [z, p, k] = butter(9, fc/fn, 'high'); % I see the filter is high pass on plotting.
Can I filter the line data using the above given and assumed values? If not, is there a way that I can filter the data using a cut-off wavelength?
The highest linear spatial frequency you can represent without aliasing is 1 wave cycle per 2 pixels. This means a spatial Nyquist frequency of 1 wave cycle per 2*(res*1e-3) meters, or 1000/(res*2) reciprocal meters. (Confront this with temporal frequencies, which are measured in reciprocal seconds a.k.a. hertz).
In terms of wavelengths: the shortest wave you can represent without aliasing is 2 pixels long per wave cycle. This means a spatial "Nyquist wavelength" of res*2e-3 meters. (Confront this with temporal "wavelengths" a.k.a. periods, which are measured in seconds.)
If you want to set a cutoff wavelength of 10 mm, that corresponds to a spatial frequency of 100 reciprocal meters. Since the butter() function takes as its second input argument (Wn, the cutoff frequency) an arbitrary fraction of the (spatial) Nyquist frequency (the MATLAB documentation calls it "half the sampling rate"), you merely need to set Wn=100/(1000/(res*2)), i.e. Wn=res/5.
Even though your definition of the spatial sampling frequency is not quite correct (unless you are intentionally measuring it in reciprocal pixels), your final result ended up being equivalent to Wn=res/5, so you should be fine using the call to butter() that you indicated.

Plotting with a wrong amplitude in MATLAB

I am trying to plot an amplitude spectrum of a signal.
Here is the code:
%My signal: y = 0.001*cos(0.005*pi*t+pi/4);
A = 0.001;
T = 400;
f = 0.0025;
pi = 3.14;
syms m
m=-1:1;
wm=(1/T)*(int((0.001*cos(0.005*pi*t + pi/4))*exp(-j*m*0.005*pi*t),t,0,T));
ww=double(wm);
Amp=abs(ww);
fi=angle(ww);
w=m*2*pi/T;
f=w/(2*pi);
figure('Name','Amplitude spectrum');
stem(f,Amp,'linewidth',2,'color','r'),grid on;
title('Amplitude spectrum'), xlabel('?[rad/s]'), ylabel('|wm|');
But it's plotted with a wrong amplitude. 5x10^-4 instead of 5x10^-3.
Where did I do the mistake?
The magnitude of your plot is correct.
The magnitudes of the impulses located at the fundamental frequency come from the scale of the cosine wave and get divided by 2: 0.001 / 2 = 5e-4. This is because the cos function can be expressed using Euler's formula such that it is a combination of two complex exponentials that are both scaled by half.
Source: Wikipedia
As such, the Fourier Transform of a complex exponential at the desired frequency is a unit-length impulse (i.e. the magnitude is 1). The cosine wave can be expressed as two complex exponentials centered at the positive and negative versions of the fundamental frequency. We further scale by 1/2 due to Euler's formula and with the property of linearity for the Fourier Transform, the impulses additionally get scaled by 1/2. You further have an additional scaling factor for your cosine wave, which scales the impulses yet again. The combination of scales: (1)(1/2)(0.001) thus gives 5e-4.
There's nothing wrong with that output. Also, your scale should be in Hertz, not rad/s. This is because of the formulation of your exponential has pi in it.
I can understand why you'd want to use the symbolic toobox here, but I highly recommend using fft instead. There's no need to get a slow symbolic calculator to compute the frequency representation of a signal when the fft is a faster algorithm to do so. If you are doing this purely to verify what the theoretical magnitude response is for your signal, then that's fine but do not do this when calculating the frequency response in practice.

How can I define the period before fitting a Fourier series to discrete data using MATLAB?

I'm using MATLAB's fit function:
fourier_series=(x,y,'fourier8');
to fit an 8th order Fourier series to a set of discrete data (x,y). I need the period of the Fourier series to be 2*pi. However I can't work out how to fix this so that when I call the function it fits the series to my required period. Any suggestions would be greatly appreciated. Thanks.
Background to problem:
I am analysing video capture data of cyclist's pedalling which outputs as a cloud of joint positions in 3D space over time. The joint positions change slightly every pedal stroke. I am therefore wishing to fit Fourier series' to these joint positions and joint angles as a function of crank arm angle to find the cyclist's "average" position. The period of the Fourier series' therefore need to be constrained to be 2*pi as the "average" positions must return to the same location when the crank arm angle is zero (i.e. top dead centre, TDC) and the crank arm angle is 2*pi (i.e. TDC after one crank arm rotation).
Currently MATLAB is selecting the period to be slightly greater than 2*pi which means that when I use the Fourier series' to calculate the cyclist's position, the cyclist's position changes for the same crank arm angle on consecutive pedal strokes.
The best way to force the fit function on a certain period is to resort to a custom equation model, via fittype. Another option (that will throw a warning) is to fix the lower and upper bounds of the parameter w to the same value, and select as solution method LinearLeastSquares.
A cleaner solution is obtained by observing that, since you already know the period the fitting problem is linear in the parameters, and so you can resort to the linear least-squares method. I'll show hereafter an example of this approach.
%// Build a simple time series with period 2*pi.
t = (0:0.01:4*2*pi)';
y = sawtooth(t);
T = 2*pi;
%// Compute the angular speed and the azimuth.
Omega = 2*pi/T;
alpha = Omega*t;
%// Build the regressor matrix, with n harmonics.
n = 8;
A = ones(length(t), 2*n+1);
for i = 1:n
A(:,[2*i 2*i+1]) = [cos(i*alpha) sin(i*alpha)];
end
%// Solve the linear system.
%// The parameters are sorted as:
%// p = [y0 a1 b1 a2 b2 ...]'
%// being y0 the average of y, a_i the terms multiplying the sines
%// and b_i the terms multiplying the cosines.
p = A\y;
%// Evaluate the Fourier series.
yApprox = A*p;
%// Compare the solution with the data.
figure();
hold on;
plot(t, y, 'b');
plot(t, yApprox, 'r');

units on x axis after FFT

My signal is a static 1D pattern detected by the linear photodiode array with N pixels and pitch p.
What units will I get along the X-axis after FFT to spectrum?
If you have a signal f(x) with unit U depending on variable x with unit V. Then
the continuous Fourier transform of f has unit UV and depends on a variable with unit 1/V.
Example 1: f(x) is a Voltage with x being time. then the Fourier transform has unit Vs (or V/Hz) versus variable 1/s (or Hz).
Example 2: f(x) is a power with x being space. Then the FT has unit Wm and the x axis (which is then a wavenumber) unit 1/m (this is probably your case).
the Discrete Fourier transform (or FFT) has unit U (same as original) and depends on a discrete variable, (which has with unit 1 by definition because it is just a counter).
So the units of the X-Axis of a FFT are 1 (because it is a counter).
I included the continuous Fourier transform, because I suspect that you just confused the FFT (which is just the name of an algorithm for the discrete Fourier transform by the way) with the ordinary (continuous) Fourier transform.
Let me clarify my above question because of the shortage of initial meaningful data.
The question was related with inverse FT of a spatial interferogram (a.k.a. fringe pattern) formed from the optical radiation by a static Fourier-transform spectrometer and detected with a linear photo diode array to reconstruct finally the optical spectrum.
Therefore, the mathematically formal answer "So the units of the X-Axis of a FFT are 1 (because it is a counter)" is absolutely right.