Plottng Error Vector Must Be Same Length - matlab

So I'm Having Trouble graphing this SSB signal after I modulated it. I keep getting the Vector Length error.
function SSB = SSBMOD
%Setting Up Variables
amplitude = 1; % Defining Amplitude
tau_in = 0.010; %Defining Tau
t_in = -0.010:0.0001:0.010; % Defining Time range
Fs = 27000; %Defining Carrier Frequency
Fc = cos(2*pi*Fs*t_in); %Carrier Signal
F = 1/t_in(end)*t_in*Fs*1.25; %Setting Up Frequency Vector for Graph
Sig = ProjectSig(amplitude,tau_in,t_in); %Calling Generated Signal output Function
%Modulating The signal Using SSB AM modulation
SSB = Sig.*Fc;
%Performing Fast Fourier Transform
SSBff = fft(SSB);
%Filter Signal to SSB
for k = 1000:1800
SSBff(k) = 0;
end
%Inverse Fourier Transform to Obtain SSB Signal
SSBSig = ifft(SSBff);
%Plotting Original Signal
subplot(3,3,1);
plot(t_in,Sig,'b');
axis([t_in(1) t_in(end) -1 1]);
title('Original Signal');
xlabel('Time (Sec)');
ylabel('V(t) (V)');
grid
shg
So right here below is the graph I'm having trouble with. I don't understand why My vector Lengths are off.
%Plotting SSB Signal
subplot(3,3,2);
plot(t_in,SSBSig,'b');
axis([t_in(1) t_in(end) -1 1]);
title('Single Sideband Signal');
xlabel('Time (Sec)');
ylabel('V(t) (V)');
grid
shg
end

t is only made up of 201 elements; setting SSBff(k) to zero from k = 1000 to 1800 increases the size of SSBff to 1800 elements. 1800 =/= 201. You should either increase your definition of t so you have more elements, or change what portions of SSBff you're setting to zero
As an aside, your for loop can also be called with the one line
SSBff(1000:1800) = 0;

Related

Vector size mismatch in MATLAB

I have been trying to write down a code for an LTI system where the response is calculated from an input x(t) and impulse h(t) response.
For the part of the code below:
y = conv(x,h).*steps;
ty = 0:steps:7;
plot(ty,y);
I'm getting the following error message:
Error using plot
Vectors must be the same length.
I'm using ty = 0:steps:7; as h(t) is defined as exp(-t/2).*((t>=2)-(t>=7)) (since it extends upto t=7).
What does actually decide ty?
Convolution Using Anonymous Functions
One way to do this process is to use anonymous functions/functions handles which are indicated by the #() that holds the input parameters in this case time, t. To create truncated signals conditional statements on t can be implemented. To have a signal ranging from t=2 to t=7 seconds truncation can be done by element-wise multiplying by ((t>=2) & (t<=7)). The t vector used to plot the final result must have a time range that is the sum of the lengths of time of the signals used in the convolution process. I believe ty is the time vector to plot the output against. In this case you must ensure ty has the same length as the output y.
Length of Results = Length of System Response + Length of Input Signal
In the case below:
x(t) → length = 1s
h(t) → length = 5s (2s to 7s)
y(t) → length = 1s + 5s = 6s (2s to 8s)
Step_Size = 0.1;
Start_Time = 0; End_Time = 7;
t = Start_Time: Step_Size: End_Time;
%Input into system x(t)%
x = #(t) 1.0.*(t >= 0 & t <= 1);
subplot(3,1,2); fplot(x);
title('x(t): Input into system');
xlabel('Time (s)'); ylabel('Amplitude');
xlim([0 10]);
ylim([0 1.1]);
%System impulse response h(t)%
h = #(t) exp(-t/2).*((t>=2) & (t<=7));
subplot(3,1,1); fplot(h);
title('h(t): System impulse response');
xlabel('Time (s)'); ylabel('Amplitude');
xlim([0 10]);
y = conv(x(t),h(t)).*Step_Size;
t = linspace(0,2*max(t),length(y));
subplot(3,1,3); plot(t,y);
title('y(t): Output/System Response');
xlabel('Time (s)'); ylabel('Amplitude');

energy detector in Matlab and plot ROC

I am having a issue with the ROC plot. I am not sure which part is wrong. I appreciate your help.
I am trying to create a Energy Detector Simulation using MATLAB. I have used a sinusoid as the input corrupted by AWGN.
clc
close all
clear all
%1. Generate a sinusoid
fs=30;
t=0:1/fs:10;
A=1;
f=10;
x=A*sin(2*pi*f*t);
figure;
plot(t,x)
%2. Generate a vector of noise samples with the required power.
N=1000;
snr_dB = -10; % SNR in decibels
snr = 10.^(snr_dB./10); % Linear Value of SNR
Pf = 0.01:0.01:1; % Pf = Probability of False Alarm
%3. Add signal and noise
Y = awgn(x,snr);
figure;
plot(t,Y)
%4. Simulation to plot Probability of Detection (Pd) vs. Probability of False Alarm (Pf)
for m = 1:length(Pf)
i = 0;
for kk=1:10000 % Number of Monte Carlo Simulations
energy = abs(Y).^2; % Energy of received signal
energy_fin =(1/N).*sum(energy); % Test Statistic for the energy detection
thresh(m) = (qfuncinv(Pf(m))./sqrt(N))+ 1; % Theoretical value of Threshold, refer, Sensing Throughput Tradeoff in Cognitive Radio, Y. C. Liang
if(energy_fin >= thresh(m)) % Check whether the received energy is greater than threshold, if so, increment Pd (Probability of detection) counter by 1
i = i+1;
end
end
Pd(m) = i/kk;
end
figure;
plot(Pf, Pd)
xlabel('Pf') % x-axis label
ylabel('Pd') % y-axis label
hold on
thresh = (qfuncinv(Pf)./sqrt(N))+ 1;
Pd_the = qfunc(((thresh - (snr + 1)).*sqrt(N))./(sqrt(2.*snr + 1)));
figure
plot(Pf, Pd_the, 'r')
xlabel('Pf') % x-axis label
ylabel('Pd threshold') % y-axis label
hold on

Morlet wavelet transformation function returns nonsensical plot

I have written a matlab function (Version 7.10.0.499 (R2010a)) to evaluate incoming FT signal and calculate the morlet wavelet for the signal. I have a similar program, but I needed to make it more readable and closer to mathematical lingo. The output plot is supposed to be a 2D plot with colour showing the intensity of the frequencies. My plot seems to have all frequencies the same per time. The program does make an fft per row of time for each frequency, so I suppose another way to look at it is that the same line repeats itself per step in my for loop. The issue is I have checked with the original program, which does return the correct plot, and I cannot locate any difference beyond what I named the values and how I organized the code.
function[msg] = mile01_wlt(FT_y, f_mn, f_mx, K, N, F_s)
%{
Fucntion to perform a full wlt of a morlet wavelett.
optimization of the number of frequencies to be included.
FT_y satisfies the FT(x) of 1 envelope and is our ft signal.
f min and max enter into the analysis and are decided from
the f-image for optimal values.
While performing the transformation there are different scalings
on the resulting "intensity".
Plot is made with a 2D array and a colour code for intensity.
version 05.05.2016
%}
%--------------------------------------------------------------%
%{
tableofcontents:
1: determining nr. of analysis f, prints and readies f's to be used.
2: ensuring correct orientation of FT_y
3:defining arrays
4: declaring waveletdiagram and storage of frequencies
5: for-loop over all frequencies:
6: reducing file to manageable size by truncating time.
7: marking plot to highlight ("randproblemer")
8: plotting waveletdiagram
%}
%--------------------------------------------------------------%
%1: determining nr. of analysis f, prints and readies f's to be used.
DF = floor( log(f_mx/f_mn) / log(1+( 1/(8*K) ) ) ) + 1;% f-spectre analysed
nr_f_analysed = DF %output to commandline
f_step = (f_mx/f_mn)^(1/(DF-1)); % multiplicative step for new f_a
f_a = f_mn; %[Hz] frequency of analysis
T = N/F_s; %[s] total time sampled
C = 2.0; % factor to scale Psi
%--------------------------------------------------------------%
%2: ensuring correct orientation of FT_y
siz = size(FT_y);
if (siz(2)>siz(1))
FT_y = transpose(FT_y);
end;
%--------------------------------------------------------------%
%3:defining arrays
t = linspace(0, T*(N-1)/N, N); %[s] timespan
f = linspace(0, F_s*(N-1)/N, N); %[Hz] f-specter
%--------------------------------------------------------------%
%4: declaring waveletdiagram and storage of frequencies
WLd = zeros(DF,N); % matrix of DF rows and N columns for storing our wlt
f_store = zeros(1,DF); % horizontal array for storing DF frequencies
%--------------------------------------------------------------%
%5: for-loop over all frequencies:
for jj = 1:DF
o = (K/f_a)*(K/f_a); %factor sigma
Psi = exp(- 0*(f-f_a).*(f-f_a)); % FT(\psi) for 1 envelope
Psi = Psi - exp(-K*K)*exp(- o*(f.*f)); % correctional element
Psi = C*Psi; %factor. not set in stone
%next step fits 1 row in the WLd (3 alternatives)
%WLd(jj,:) = abs(ifft(Psi.*transpose(FT_y)));
WLd(jj,:) = sqrt(abs(ifft(Psi.*transpose(FT_y))));
%WLd(jj,:) = sqrt(abs(ifft(Psi.*FT_y))); %for different array sizes
%and emphasizes weaker parts.
%prep for next round
f_store (jj) = f_a; % storing used frequencies
f_a = f_a*f_step; % determines the next step
end;
%--------------------------------------------------------------%
%6: reducing file to manageable size by truncating time.
P = floor( (K*F_s) / (24*f_mx) );%24 not set in stone
using_every_P_point = P %printout to cmdline for monitoring
N_P = floor(N/P);
points_in_time = N_P %printout to cmdline for monitoring
% truncating WLd and time
WLd2 = zeros(DF,N_P);
for jj = 1:DF
for ii = 1:N_P
WLd2(jj,ii) = WLd(jj,ii*P);
end
end
t_P = zeros(1,N_P);
for ii = 1:N_P % set outside the initial loop to reduce redundancy
t_P(ii) = t(ii*P);
end
%--------------------------------------------------------------%
%7: marking plot to highlight boundary value problems
maxval = max(WLd2);%setting an intensity
mxv = max(maxval);
% marks in wl matrix
for jj= 1:DF
m = floor( K*F_s / (P*pi*f_store(jj)) ); %finding edges of envelope
WLd2(jj,m) = mxv/2; % lower limit
WLd2(jj,N_P-m) = mxv/2;% upper limit
end
%--------------------------------------------------------------%
%8: plotting waveletdiagram
figure;
imagesc(t_P, log10(f_store), WLd2, 'Ydata', [1 size(WLd2,1)]);
set(gca, 'Ydir', 'normal');
xlabel('Time [s]');
ylabel('log10(frequency [Hz])');
%title('wavelet power spectrum'); % for non-sqrt inensities
title('sqrt(wavelet power spectrum)'); %when calculating using sqrt
colorbar('location', 'southoutside');
msg = 'done.';
There are no error message, so I am uncertain what exactly I am doing wrong.
Hope I followed all the guidelines. Otherwise, I apologize.
edit:
my calling program:
% establishing parameters
N = 2^(16); % | number of points to sample
F_s = 3.2e6; % Hz | samplings frequency
T_t = N/F_s; % s | length in seconds of sample time
f_c = 2.0e5; % Hz | carrying wave frequency
f_m = 8./T_t; % Hz | modulating wave frequency
w_c = 2pif_c; % Hz | angular frequency("omega") of carrying wave
w_m = 2pif_m; % Hz | angular frequency("omega") of modulating wave
% establishing parameter arrays
t = linspace(0, T_t, N);
% function variables
T_h = 2*f_m.*t; % dimless | 1/2 of the period for square signal
% combined carry and modulated wave
% y(t) eq. 1):
y_t = 0.5.*cos(w_c.*t).*(1+cos(w_m.*t));
% y(t) eq. 2):
% y_t = 0.5.*cos(w_c.*t)+0.25*cos((w_c+w_m).*t)+0.25*cos((w_c-w_m).*t);
%square wave
sq_t = cos(w_c.*t).*(1 - mod(floor(t./T_h), 2)); % sq(t)
% the following can be exchanged between sq(t) and y(t)
plot(t, y_t)
% plot(t, sq_t)
xlabel('time [s]');
ylabel('signal amplitude');
title('plot of harmonically modulated signal with carrying wave');
% title('plot of square modulated signal with carrying wave');
figure()
hold on
% Fourier transform and plot of freq-image
FT_y = mile01_fftplot(y_t, N, F_s);
% FT_sq = mile01_fftplot(sq_t, N, F_s);
% Morlet wavelet transform and plot of WLdiagram
%determining K, check t-image
K_h = 57*4; % approximation based on 1/4 of an envelope, harmonious
%determining f min and max, from f-image
f_m = 1.995e5; % minimum frequency. chosen to showcase all relevant f
f_M = 2.005e5; % maximum frequency. chosen to showcase all relevant f
%calling wlt function.
name = 'mile'
msg = mile01_wlt(FT_y, f_m, f_M, K_h, N, F_s)
siz = size(FT_y);
if (siz(2)>siz(1))
FT_y = transpose(FT_y);
end;
name = 'arnt'
msg = arnt_wltransf(FT_y, f_m, f_M, K_h, N, F_s)
The time image has a constant frequency, but the amplitude oscillates resempling a gaussian curve. My code returns a sharply segmented image over time, where each point in time holds only 1 frequency. It should reflect a change in intensity across the spectra over time.
hope that helps and thanks!
I found the error. There is a 0 rather than an o in the first instance of Psi. Thinking I'll maybe rename the value as sig or something. besides this the code works. sorry for the trouble there

Fourier transform and LTI filter and frequency response in Matlab

I'm new to Matlab for LTI signal processing and wondering if anyone can help with something that I'm sure is meant to be basic. I've spent hours and hours researching and obtaining background information and still cannot obtain a clear path to tackle these problems. So far, from scratch, I have generated a signal required and managed to use the fft function to produce the signal's DFT:
function x = fourier_rikki(A,t,O)
Fs = 1000;
t = 0:(1/Fs):1;
A = [0.5,0,0.5];
N = (length(A) - 1)/2;
x = zeros(size(t));
f1 = 85;
O1 = 2*pi*f1;
for k = 1:length(A)
x1 = x + A(k)*exp(1i*O1*t*(k-N-1));
end
f2 = 150;
O2 = 2*pi*f2;
for k = 1:length(A);
x2 = x + A(k)*exp(1i*O2*t*(k-N-1));
end
f3 = 330;
O3 = 2*pi*f3;
for k = 1:length(A);
x3 = x + A(k)*exp(1i*O3*t*(k-N-1));
end
signal = x1 + x2 + x3;
figure(1);
subplot(3,1,1);
plot(t, signal);
title('Signal x(t) in the Time Domain');
xlabel('Time (Seconds)');
ylabel('x(t)');
X = fft(signal); %DFT of the signal
subplot(3,1,2);
plot(t, X);
title('Power Spectrum of Discrete Fourier Transform of x(t)');
xlabel('Time (Seconds)');
ylabel('Power');
f = linspace(0, 1000, length(X)); %?
subplot(3,1,3);
plot(f, abs(X)); %Only want the positive values
title('Spectral Frequency');
xlabel('Frequency (Hz)'); ylabel('Power');
end
At this stage, I'm assuming this is correct for:
"Generate a signal with frequencies 85,150,330Hz using a sampling frequency of 1000Hz - plot 1seconds worth of the signal and its Discrete Fourier Transform."
The next step is to "Find the frequency response of an LTI system that filters out the higher and lower frequencies using the Fourier Transform". I'm stuck trying to create an LTI system that does that! I have to be left with the 150Hz signal, and I'm guessing I perform the filtering on the FFT, perhaps using conv.
My course is not a programming course - we are not assessed on our programming skills and I have minimal Matlab experience - basically we have been left to our own devices to struggle through, so any help would be greatly appreciated! I am sifting through tonnes of different examples and searching Matlab functions using 'help' etc, but since each one is different and does not have a break down of the variables used, explaining why certain parameters/values are chosen etc. it is just adding to the confusion.
Among many (many) others I have looked at:
http://www.ee.columbia.edu/~ronw/adst-spring2010/lectures/matlab/lecture1.html
http://gribblelab.org/scicomp/09_Signals_and_sampling.html section 10.4 especially.
As well as Matlab Geeks examples and Mathworks Matlab function explanations.
I guess the worst that can happen is that nobody answers and I continue burning my eyeballs out until I manage to come up with something :) Thanks in advance.
I found this bandpass filter code as a Mathworks example, which is exactly what needs to be applied to my fft signal, but I don't understand the attenuation values Ast or the amount of ripple Ap.
n = 0:159;
x = cos(pi/8*n)+cos(pi/2*n)+sin(3*pi/4*n);
d = fdesign.bandpass('Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2',1/4,3/8,5/8,6/8,60,1,60);
Hd = design(d,'equiripple');
y = filter(Hd,x);
freq = 0:(2*pi)/length(x):pi;
xdft = fft(x);
ydft = fft(y);
plot(freq,abs(xdft(1:length(x)/2+1)));
hold on;
plot(freq,abs(ydft(1:length(x)/2+1)),'r','linewidth',2);
legend('Original Signal','Bandpass Signal');
Here is something you can use as a reference. I think I got the gist of what you were trying to do. Let me know if you have any questions.
clear all
close all
Fs = 1000;
t = 0:(1/Fs):1;
N = length(t);
% 85, 150, and 330 Hz converted to radian frequency
w1 = 2*pi*85;
w2 = 2*pi*150;
w3 = 2*pi*330;
% amplitudes
a1 = 1;
a2 = 1.5;
a3 = .75;
% construct time-domain signals
x1 = a1*cos(w1*t);
x2 = a2*cos(w2*t);
x3 = a3*cos(w3*t);
% superposition of 85, 150, and 330 Hz component signals
x = x1 + x2 + x3;
figure
plot(t(1:100), x(1:100));
title('unfiltered time-domain signal, amplitude vs. time');
ylabel('amplitude');
xlabel('time (seconds)');
% compute discrete Fourier transform of time-domain signal
X = fft(x);
Xmag = 20*log10(abs(X)); % magnitude spectrum
Xphase = 180*unwrap(angle(X))./pi; % phase spectrum (degrees)
w = 2*pi*(0:N-1)./N; % normalized radian frequency
f = w./(2*pi)*Fs; % radian frequency to Hz
k = 1:N; % bin indices
% plot magnitude spectrum
figure
plot(f, Xmag)
title('frequency-domain signal, magnitude vs. frequency');
xlabel('frequency (Hz)');
ylabel('magnitude (dB)');
% frequency vector of the filter. attenuates undesired frequency components
% and keeps desired components.
H = 1e-3*ones(1, length(k));
H(97:223) = 1;
H((end-223):(end-97)) = 1;
% plot magnitude spectrum of signal and filter
figure
plot(k, Xmag)
hold on
plot(k, 20*log10(H), 'r')
title('frequency-domain signal (blue) and filter (red), magnitude vs. bin index');
xlabel('bin index');
ylabel('magnitude (dB)');
% filtering in frequency domain is just multiplication
Y = X.*H;
% plot magnitude spectrum of filtered signal
figure
plot(f, 20*log10(abs(Y)))
title('filtered frequency-domain signal, magnitude vs. frequency');
xlabel('frequency (Hz)');
ylabel('magnitude (dB)');
% use inverse discrete Fourier transform to obtain the filtered time-domain
% signal. This signal is complex due to imperfect symmetry in the
% frequency-domain, however the imaginary components are nearly zero.
y = ifft(Y);
% plot overlay of filtered signal and desired signal
figure
plot(t(1:100), x(1:100), 'r')
hold on
plot(t(1:100), x2(1:100), 'linewidth', 2)
plot(t(1:100), real(y(1:100)), 'g')
title('input signal (red), desired signal (blue), signal extracted via filtering (green)');
ylabel('amplitude');
xlabel('time (seconds)');
Here is the end result...

Graphing the Short-time Fourier Transform (note the window size and step) in matlab

Need help since kind of lost on this. I am trying to graph the code below i have in which I made a white noise and used STFT to do the bandpass filtering but now I need to graph the signal in to two graphs for each channel. The result should be graphs. For graph 1a., the horizontal axis should be frequency, the vertical axis should be amplitude. For (2).b, the horizontal axis should be time, the vertical axis should be frequency, and express the amplitude using color.
function newwhitenoise()
L = 5000; %Sample length for the random signal
Pause = 10000; %Sample Pause Gap
mu = 0;
sigma = 2;
%Need to see left signal is not displaying
Left_signal = sigma*randn(L,1) + mu;
Right_signal = sigma*randn(L,1) + mu;
Long_signal = [Left_signal zeros(L,1); zeros(Pause,2); zeros(L,1) Right_signal];
%Player Object
soundRecord(Long_signal);
disp([Left_signal zeros(L,1)]);
%sound(Long_signal, Fs);
%Plots subplots in graph
%figure
%subplot(211);
%plot(Left_signal, 'b'); grid on;
%subplot(212);
%plot(Right_signal, 'r'); grid on;
end
function signalplayer(signal)
%load(signal);
fs = 44100; %Sample Frequency
obj = audioplayer(signal,fs);
play(obj);
end
function soundRecord (signal)
fs = 44100; %Sample Frequency
recObj = audiorecorder(44100, 16, 2);
get(recObj)
%save sound to wave file
%filename = 'location.flac';
audiowrite('input.wav',signal, fs);
if ~exist('inFile')
inFile = 'input.wav';
end
if ~exist('outFile')
outFile = 'output.wav';
end
if ~exist('frameWidth')
frameWidth = 4096; % size of FFT frame, better be a power of 2
end
frameHop = frameWidth/2;
analWindow = hanning(frameWidth);
[inBuffer, Fs] = wavread(inFile);
x = [inBuffer(:,1); linspace(0, 0, frameWidth)']; % use left channel only, zeropad one frame at the end
clear inBuffer;
numSamples = length(x);
numFrames = floor(numSamples/frameHop)-1;
% disp(frameWidth);
% disp(numSamples);
% disp(frameHop);
% disp(numFrames);
% disp(size(analWindow));
% disp(size(transpose(analWindow)));
y = linspace(0, 0, numSamples)';
n = 0; % init sample pointer. unlike MATLAB, i like counting from 0
for frameIndex = 1:numFrames
xWindowed = x(n+1:n+frameWidth) .* analWindow; % get and window the input audio frame
X = fft(fftshift(xWindowed)); % do the FFT
Y = X; % copy the input spectrum to output
% do whatever processing to Y that you like
yWindowed = fftshift(real(ifft(Y))); % convert back to time domain, toss the imaginary part
%disp(size(x(1:frameWidth)));
%disp(size(yWindowed));
y(n+1:n+frameWidth) = y(n+1:n+frameWidth) + yWindowed;
n = n + frameHop;
end
wavwrite(y, Fs, 'output.wav');
For graph 1 try pwelch and for graph 2 try spectrogram.
pwelch is basically the average of the squared magnitude of the STFT. The spectrogram function returns the STFT of the signal thus it operates on the signal in the time domain.
Both functions are called with the same input parameters and when called with no output, plot the result on the current axes.
If you want the frequency axis to be the vertical (y) in graph 2, use the option 'yaxis' in the call for spectrogram. I suggest you look at the documentation of both functions.