How can I debug the following Matlab code? - matlab

The error
File: parameter_estimation_1.m Line: 8 Column: 10
Unexpected MATLAB expression.
crops up when I run the following MATLAB code:
T = 0:0.25:5; % time vector (row)
T = T'; % time vector (column)
seed = [3;0.5]; % seed for noise generation
randn('state',seed); % using the same seed each time
uu = 0.5 1 0.25*randn(length(T),1); % mean of 0.5 with variance
% of 0.25
U = 2*round(uu)-1; % creates PRBS with -1 and 1 values %
sim('est_vdv'); % runs simulation of linear van de vusse % diagram
figure(1); % plot input-output data
subplot(2,1,1),plot(tp,yp,'k',t,y,'ko');
xlabel('time, min'), ylabel('y')
title('PRBS estimation example')
subplot(2,1,2),plot(tp,up,'k'); xlabel('time, min'),ylabel('u')
axis([0 5 -1.1 1.1])
% % generate phi matrix for estimation
for j = 4:22;
phi(j-3,:) = [y(j-2) y(j-3) u(j-2) u(j-3)];
end
%
theta = inv(phi'*phi)*phi'*y(3:21) % estimate parameters
num = [theta(3) theta(4)]; % numerator of discrete transfer function
den = [1 -theta(1) -theta(2)]; % denominator of discrete transfer function
sysd = tf(num,den,0.25) % create discrete tf object
tzero(sysd) % calculate zeros
pole(sysd) % calculate poles
syszpk = zpk(sysd) % zero-pole-k form
This code is supposed to run in tandem with a SIMULINK model titled "est_vdv" to estimate the parameters of a model.
How should I deal with this error?

Thanks Friends for your suggestions, I have been able to figure out what went wrong with the 5th line, it should have been
uu=0.5+0.25.*randn(length(T),1)
Sorry, it was wrongly indicated that the error was in the 8th line.

Related

Obtaining steady state solution for spring mass dashpot system

I'm trying to solve the following problem using MATLAB but I faced multiple issues. The plot I obtained doesn't seem right even though I tried to obtain the steady-state solution, I got a plot that doesn't look steady.
The problem I'm trying to solve
The incorrect plot I got.
and here is the code
% system parameters
m=1; k=1; c=.1; wn=sqrt(k/m); z=c/2/sqrt(m*k); wd=wn*sqrt(1-z^2);
% initial conditions
x0=0; v0=0;
%% time
dt=.001; tMax=8*pi; t=0:(tMax-0)/999:tMax;
% input
A=1
omega=(2*pi)/10
F=A/2-(4*A/pi^2)*cos(omega*t); Fw=fft(F);
F=k*A*cos(omega*t); Fw=fft(F);
% normalize
y = F/m;
% compute coefficients proportional to the Fourier series coefficients
Yw = fft(y);
% setup the equations to solve the particular solution of the differential equation
% by the method of undetermined coefficients
N=1000
T=10
k = [0:N/2];
w = 2*pi*k/T;
A = wn*wn-w.*w;
B = 2*z*wn*w;
% solve the equation [A B;-B A][real(Xw); imag(Xw)] = [real(Yw); imag(Yw)] equation
% Note that solution can be obtained by writing [A B;-B A] as a scaling + rotation
% of a 2D vector, which we solve using complex number algebra
C = sqrt(A.*A+B.*B);
theta = acos(A./C);
Ywp = exp(j*theta)./C.*Yw([1:N/2+1]);
% build a hermitian-symmetric spectrum
Xw = [Ywp conj(fliplr(Ywp(2:end-1)))];
% bring back to time-domain (function synthesis from Fourier Series coefficients)
x = ifft(Xw);
figure()
plot(t,x)
Your forcing function doesn't look like the triangle wave in the problem. I edited the %% time section of your code into the following and appeared to give a steady state response.
%% time
TP = 10; % forcing time period (10 s)
dt=.001;
tMax= 3*TP; % needs to be multiple of the time period
t=0:(tMax-0)/999:tMax;
% input
A=1; % Forcing amplitude
omega=(2*pi)/TP;
% forcing is a triangle wave
% generate a triangle wave with min/max values of 0/1.
F = 0*t;
for i = 1:length(t)
if mod(t(i), TP) <= TP/2
F(i) = mod(t(i), TP)/(TP/2);
else
F(i) = 2 - mod(t(i), TP)/(TP/2);
end
end
F = F*A; % scale triangle wave by amplitude
% you can also use MATLAB's sawtooth() function if you have the signal
% processing toolbox

Matlab : What is the BER performance of Constant Modulus Algorithm and issue in filter function

I need help in plotting the Bit error curve or the symbol error curve for BPSK modulation scheme for varying Signal to Noise ratios or Eb/N0. The plot should show the simulated versus the theoretical curve, but I cannot figure out how to mitigate the problems when using the Constant Modulus Algorithm as an Equalizer which are:
(1)
Error using *
Inner matrix dimensions must agree.
Error in BER_BPSK_CMA (line 50)
yy = w'*x;
(2) I want to use the filter function instead of conv in order to model a moving average channel model, chanOut = filter(ht,1,s). But, when I use filter, I am getting an error. How can I use filter function here?
(3) Bit error rate calculation
UPDATED Code with the Problem 1 solved. However, I am still unable to use filter and unsure if BER curve is proper or not.
Below is the code I wrote:
% Script for computing the BER for BPSK modulation in 3 tap ISI
% channel
clear
N = 10^2; % number of bits or symbols
Eb_N0_dB = [0:15]; % multiple Eb/N0 values
K = 3; %number of users
nTap = 3;
mu = 0.001;
ht = [0.2 0.9 0.3];
L = length(ht);
for ii = 1:length(Eb_N0_dB)
% Transmitter
ip = rand(1,N)>0.5; % generating 0,1 with equal probability
s = 2*ip-1; % BPSK modulation 0 -> -1; 1 -> 0
% Channel model, multipath channel
chanOut = conv(s,ht);
% chanOut = filter(ht,1,s); %MA
n = 1/sqrt(2)*[randn(1,N+length(ht)-1) + j*randn(1,N+length(ht)-1)]; % white gaussian noise, 0dB variance
% Noise addition
y = chanOut + 10^(-Eb_N0_dB(ii)/20)*n; % additive white gaussian noise
%CMA
Le =20; %Equalizer length
e = zeros(N,1); % error
w = zeros(Le,1); % equalizer coefficients
w(Le)=1; % actual filter taps are flipud(w)!
yd = zeros(N,1);
r = y';
% while(1)
for i = 1:N-Le,
x = r(i:Le+i-1);
%x = r(i:(Le+i-1));
yy = w'*x;
yd(i)= yy;
e(i) = yy^2 - 1;
mse_signal(ii,i) = mean(e.*e);
w = w - mu * e(i) * yy * x;
end
sb=w'*x; % estimate symbols (perform equalization)
% receiver - hard decision decoding
ipHat = real(sb)>0;
% counting the errors
nErr_CMA(ii) = size(find([ip- ipHat]),2);
% calculate SER
end
simBer_CMA = nErr_CMA/N;
theoryBer = 0.5*erfc(sqrt(10.^(Eb_N0_dB/10))); % theoretical ber
for i=1:length(Eb_N0_dB),
tmp=10.^(i/10);
tmp=sqrt(tmp);
theoryBer(i)=0.5*erfc(tmp);
end
figure
semilogy(theoryBer,'b'),grid;
hold on;
semilogy(Eb_N0_dB,simBer_CMA,'r-','Linewidth',2);
%axis([0 14 10^-5 0.5])
grid on
legend('sim-CMA');
xlabel('Eb/No, dB');
ylabel('Bit Error Rate');
title('Bit error probability curve for BPSK in ISI with CMA equalizer');
There's an error in these three lines:
sb=w'*x; % estimate symbols (perform equalization)
% receiver - hard decision decoding
ipHat = real(sb)>0;
they worked inside the while loop but you are now performing a post-estimation, so the correct lines are:
sb=conv(w,y); % estimate symbols (perform equalization)
% receiver - hard decision decoding
ipHat = real(sb(Le+1:end-1))>0; % account for the filter delay
There is still some issue with the output... but I can't go further in the analisys.
Your first problem is easily solved: change the line to
x = y(i:(Le+i-1));
Your call of filter looks OK. Which error do you get?
Maybe this is a place to start looking.
Or here (would Fig. 4 be the type of plot you're after?)

SNR plot and rectangular fit (Matlab)

I have attached 3 images and the SNR function to calculate the SNR between each of the images. How can I plot this SNR so its easy to understand the levels from the plot rather than just numbers.
SNR function:
% function to calculate the drop in SNR between Best focussed image to
% slightly out of focus image. The value is presented in dB scale and amplitude
%for comparison.
% Terms:
%%Signal image = best focussed image
%%Noise image = slight off focussed image
%%Dark scan = for future reference with respect to Signal image
%---------------Define function to calcuate SNR---------------%
function SNR = SNR(signal, noise, typ, noisy)
% snr - calculate signal-to-noise ratio in decibel or amplitude
%
% Syntax: SNR = snr(signal, noise)
% SNR = snr(signal, signal_noise, typ, true)
%
% Inputs:
% signal - signal amplitude
% noise - noise amplitude or noisy signal
% typ - type of SNR (default:'db' to decibel or 'amp' to amplitude)
% noisy - eval noise flag (use noise as noisy signal)
%
% Outputs:
% SNR - Signal-to-Noise Ratio
%
% Example:
% dt = 0.01;
% T = 0:dt:10;
% sig = sin(2*pi*T);
% noisy = sig + (0 + .5 * randn(1,length(T))); % error mean 0 and sd .5
% snr_db = snr(sig,noisy,'db',true)
%
% Other m-files required: none
% Subfunctions: rms
%------------------------------- BEGIN CODE -------------------------------
if ~exist('typ', 'var')
typ = 'db';
end
if ~exist('noisy', 'var')
noisy = false;
end
if noisy % eval noise
noise = signal-noise;
end
if strcmp(typ,'db')
SNR = 20*log10(rms(signal)/rms(noise));
elseif strcmp(typ,'amp')% string comparison for type value.
SNR = rms(signal)/rms(noise);
end
end
%-------------------------------- END CODE --------------------------------
RMS function
function RMS= rms(varargin)
%
% Written by Phillip M. Feldman March 31, 2006
%
% rms computes the root-mean-square (RMS) of values supplied as a
% vector, matrix, or list of discrete values (scalars). If the input is
% a matrix, rms returns a row vector containing the RMS of each column.
% David Feldman proposed the following simpler function definition:
%
% RMS = sqrt(mean([varargin{:}].^2))
%
% With this definition, the function accepts ([1,2],[3,4]) as input,
% producing 2.7386 (this is the same result that one would get with
% input of (1,2,3,4). I'm not sure how the function should behave for
% input of ([1,2],[3,4]). Probably it should produce the vector
% [rms(1,3) rms(2,4)]. For the moment, however, my code simply produces
% an error message when the input is a list that contains one or more
% non-scalars.
if (nargin == 0)
error('Missing input.');
end
% Section 1: Restructure input to create x vector.
if (nargin == 1)
x= varargin{1};
else
for i= 1 : size(varargin,2)
if (prod(size(varargin{i})) ~= 1)
error(['When input is provided as a list, ' ...
'list elements must be scalar.']);
end
x(i)= varargin{i};
end
end
% Section 2: Compute RMS value of x.
RMS= sqrt (mean (x .^2) );
Script
% sig= best focussed image
% noisy= off focussed image
% dark = no light image
%-------------------------
% calculate SNR between:
% sig and noise
% signal and dark
% noise and dark
clear
sig = rgb2gray(imread('S1-BestFocus.bmp'));
noisy = rgb2gray(imread('S1-OffFocus.bmp'));
dark=rgb2gray(imread('DarkScan.bmp'));
sig_noise = SNR(sig,noisy,'db',true);
sig_dark = SNR(sig,dark,'db',true);
noise_dark = SNR(noisy,dark,'db',true);
Figures:
figures for calculation
I am imaging a slit of 15-18 microns in width and 1mm in length, the slit is not uniform, hence I have to check how much is the variation along the length of the slit in terms of width. What is the best possible way to get the measurement. ( one method is to use rectangular fit).

Reconstructing time series from FFT in MATLAB

I am trying to reconstruct the sunspots signal from the FFT, the time series and periodogram are in the following site http://www.mathworks.com/help/matlab/examples/using-fft.html . I wrote the following code but the result were not similar to original wave:
YY=Y(1:floor(n/2))
% magnitude
mag_fft = 2*abs(YY)/length(Y);
% phase angle
ang_fft = angle(YY);
[new_mag,new_i]=sort(mag_fft,'descend');
new_ang=ang_fft(new_i);
new_freq=freq(new_i)
wave=zeros(1,length(YY));
wave=new_mag(1);
t=1:length(YY)
for(i=1:70)
wave=wave+new_mag(i).*sin(2*pi*new_freq(i)*t+new_ang(i));
end
wave=wave-mag_fft(1)
figure;plot(year(t),wave,'-b')
hold on;plot(year(t),relNums(t),'-r')
any ideas?
%http://www.mathworks.com/help/matlab/examples/using-fft.html
% sunspots
% sunspots have period of 10 years
%%
clc;clear all;close all;
load sunspot.dat
year=sunspot(:,1);
relNums=sunspot(:,2);
figure;plot(year,relNums)
title('Sunspot Data')
plot(year(1:50),relNums(1:50),'b.-');
yfft = fft(relNums);%figure;plot(ifft(yfft)-data1d,'r')
%yfft = fft(data1d); iyfft=ifft(yfft);
[sum(relNums) yfft(1)]
yfft(1)=[]; % we grid rid of the first value as it corresponeding to zero frequency.
N=length(yfft)+1;
yfft=yfft.*2./N;
%%
power_fft = abs(yfft);power1_fft = sqrt(yfft.*conj(yfft));
figure;plot(power_fft,'-b');hold on;plot(power_fft,'rO')
ang_fft = angle(yfft);real_fft= real(yfft);imag_fft= imag(yfft);
figure;plot(real_fft);hold on;plot(imag_fft,'-r')
figure;plot(angle(yfft))
ph = (180/pi)*unwrap(ang_fft); % phase in degrees
% Now the total length of the per and all other powers should be N-1 because there is no
% more corresponding poweres and phases, and the number of frequencies before the nequiest is
Nneq=length(N./(1:N/2));
Nm1=N-1; per=N./(1:Nm1); freq=1./per;
[per'/12 power_fft(1:Nm1)/100 ] % so as to display the period in years
%% ytyt
ndat=length(relNums);
x=0:ndat-1;
sumharmony1(1:Nneq,1:ndat)=0;
sumharmony2(1:Nneq,1:ndat)=0;
for i=1:Nneq
% those two forms are equal, the last one is called the cos form.
% sumharmony1(i,:)=sumharmony1(i,:)+real_fft(i)*cos(2*pi*x/(per(i)))- imag_fft(i)*sin(2*pi*x/(per(i)));
sumharmony1(i,:)=sumharmony1(i,:)+power_fft(i)*cos(2*pi*x./(per(i))+ang_fft(i));
end
y1 =sum(relNums)/N+ sum(sumharmony1);
%y2 =sum(tmp)/N+ sum(sumharmony2);
figure;plot(relNums);hold on; plot( y1, 'r');
figure;plot((relNums-y1')) % However, the excellent results, we couldnot yet reach to the that of the built in function ifft.
figure;plot(relNums(1:100),'-ob');hold on; plot( y1(1:100), 'r');
% note that we multiply by 2 because of using the window hanning.enter code here

bootstrap data in confidence interval MATLAb

I tried this as well:
plot(x(bootsam(:,100)),y(bootsam(:,100)), 'r*') but it was exactly the same to my data! I want to resample my data in 95% confidence interval .
But it seems this command bootstrp doesn't work alone, it needs some function or other commands to combine. Would you help me to figure it out?
I would like to generate some data randomly but behave like my function around the original data, I attached a plot which original data which are red and resampled data are in blue and green colors.
Generally, I would like to use bootstrap to find error for my best-fit parameters. I read in this book:
http://books.google.de/books?id=ekyupqnDFzMC&lpg=PA131&vq=bootstrap&hl=de&pg=PA130#v=onepage&q&f=false
other methods for error analysis my fitted parameters are appreciated.
I suggest you start this way and then adapt it to your case.
% One step at a time.
% Step 1: Suppose you generate a simple linear deterministic trend with
% noise from the standardized Gaussian distribution:
N = 1000; % number of points
x = [(1:N)', ones(N, 1)]; % x values
b = [0.15, 157]'; % parameters
y = x * b + 10 * randn(N, 1); % linear trend with noise
% Step 2: Suppose you want to fit y with a linear equation:
[b_hat, bint1] = regress(y, x); % estimate parameters with linear regression
y_fit = x * b_hat; % calculate fitted values
resid = y - y_fit; % calculate residuals
plot(x(:, 1), y, '.') % plot
hold on
plot(x(:, 1), y_fit, 'r', 'LineWidth', 5) % fitted values
% Step 3: use bootstrap approach to estimate the confidence interval of
% regression parameters
N_boot = 10000; % size of bootstrap
b_boot = bootstrp(N_boot, #(bootr)regress(y_fit + bootr, x), resid); % bootstrap
bint2 = prctile(b_boot, [2.5, 97.5])'; % percentiles 2.5 and 97.5, a 95% confidence interval
% The confidence intervals obtained with regress and bootstrp are
% practically identical:
bint1
bint2