since i don't have sinc function in my MATLAB,
I implemented that function as shown below
%% time specificactions:
Fs=10000; dt=1/Fs; t=(-0.1:dt:0.1-dt)'; N=size(t,1);
%message signal
mt=(sin(pi*100*t))./(pi*100*t);
%% frequency specifications
dF=Fs/N;
f=-Fs/2:dF:Fs/2-dF;
M=fftshift(fft(mt));
plot(f,abs(M)/N);
but the figure shows me nothing but blank, so i looked up the variable table and it is filled with NaN.
One thing I don't understand that is that the exactly same procedure worked pretty well when the function i want to fourier transform was just cosine function.
You have a wrongly defined sinc function, as when t=0 it outputs NaN.
you can check that doing any(isnan(mt)) in your code.
To define properly the function do
mt(find(t==0))=1;
That will make your code output
You may want to reconsider the parameters in order to see better the square wave.
the source code of sinc function in Matlab:
function y=sinc(x)
%SINC Sin(pi*x)/(pi*x) function.
% SINC(X) returns a matrix whose elements are the sinc of the elements
% of X, i.e.
% y = sin(pi*x)/(pi*x) if x ~= 0
% = 1 if x == 0
% where x is an element of the input matrix and y is the resultant
% output element.
%
% % Example of a sinc function for a linearly spaced vector:
% t = linspace(-5,5);
% y = sinc(t);
% plot(t,y);
% xlabel('Time (sec)');ylabel('Amplitude'); title('Sinc Function')
%
% See also SQUARE, SIN, COS, CHIRP, DIRIC, GAUSPULS, PULSTRAN, RECTPULS,
% and TRIPULS.
% Author(s): T. Krauss, 1-14-93
% Copyright 1988-2004 The MathWorks, Inc.
% $Revision: 1.7.4.1 $ $Date: 2004/08/10 02:11:27 $
i=find(x==0);
x(i)= 1; % From LS: don't need this is /0 warning is off
y = sin(pi*x)./(pi*x);
y(i) = 1;
Related
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
I've written the following code:
function [a1,b1,a0,b0] = Conformal_2D(x_input,y_input,X_output,Y_output)
%%
% Calculates parameters $a,b,a_0,b_0$ in the following equation using least
% squares
%%
%
% $$X=a_1x+b_1y+a_0$$
%
% $$X=-b_1x+a_1y+b_0$$
%%
% *Arguments:*
%
% x_input is a $n\times 1$ matrix containing x coordinate of control points
% in the input space
%
% y_input is a $n\times 1$ matrix containing y coordinate of control points
% in the input space
%
% x_output is a $n\times 1$ matrix containing x coordinate of control points
% in the output space
%
% y_output is a $n\times 1$ matrix containing y coordinate of control points
% in the output space
%%
NumberOfPoints = size(x_input,1);
A = zeros(2*NumberOfPoints,1); % Coefficient matrix in AX = L
L = zeros(2*NumberOfPoints,1); % Right-hand matrix in AX = L
for i = 1:NumberOfPoints
A(2*i-1,1:4) = [x_input(i,1) y_input(i,1) 1 0];
end
end
When I press 'Publish' button, I get:
What's the problem with that line?
Not sure if this is the best workaround, but I managed to publish the function with the following script. Of course, you will use your own entries for x_input, y_inpyt, etc. Make sure that you save the following script in a file not named Conformal_2D.m.
Conformal_2D([3;2;1],[5;6;7],[11;12;13],[14;15;16]);
function [a1,b1,a0,b0] = Conformal_2D(x_input,y_input,X_output,Y_output)
%%
% Calculates parameters $a,b,a_0,b_0$ in the following equation using least
% squares
%%
%
% $$X=a_1x+b_1y+a_0$$
%
% $$X=-b_1x+a_1y+b_0$$
%%
% *Arguments:*
%
% x_input is a $n\times 1$ matrix containing x coordinate of control points
% in the input space
%
% y_input is a $n\times 1$ matrix containing y coordinate of control points
% in the input space
%
% x_output is a $n\times 1$ matrix containing x coordinate of control points
% in the output space
%
% y_output is a $n\times 1$ matrix containing y coordinate of control points
% in the output space
%%
NumberOfPoints = size(x_input,1);
A = zeros(2*NumberOfPoints,1); % Coefficient matrix in AX = L
L = zeros(2*NumberOfPoints,1); % Right-hand matrix in AX = L
for i = 1:NumberOfPoints
A(2*i-1,1:4) = [x_input(i,1) y_input(i,1) 1 0];
end
end
When publishing, MATLAB runs the code by default. Of course, your function has input arguments that will not be set in this case (see this other question).
There are a few ways around this. Juanchito's answer illustrates one: don't publish a function, publish a script.
Alternatively, publish the function without executing it:
publish('Conformal_2D.m','evalCode',false)
Or, give MATLAB the right declarations to evaluate before executing the function's content:
publish('Conformal_2D.m','codeToEvaluate','x_input=1; y_input=2; X_output=3; Y_output=4')
(do adjust those values, of course).
I've got this code:
function [sigma,shrinkage]=covMarket(x,shrink)
% function sigma=covmarket(x)
% x (t*n): t iid observations on n random variables
% sigma (n*n): invertible covariance matrix estimator
%
% This estimator is a weighted average of the sample
% covariance matrix and a "prior" or "shrinkage target".
% Here, the prior is given by a one-factor model.
% The factor is equal to the cross-sectional average
% of all the random variables.
% The notation follows Ledoit and Wolf (2003)
% This version: 04/2014
% de-mean returns
t=size(x,1);
n=size(x,2);
meanx=mean(x);
x=x-meanx(ones(t,1),:);
xmkt=mean(x')';
sample=cov([x xmkt])*(t-1)/t;
covmkt=sample(1:n,n+1);
varmkt=sample(n+1,n+1);
sample(:,n+1)=[];
sample(n+1,:)=[];
prior=covmkt*covmkt'./varmkt;
prior(logical(eye(n)))=diag(sample);
if (nargin < 2 | shrink == -1) % compute shrinkage parameters
c=norm(sample-prior,'fro')^2;
y=x.^2;
p=1/t*sum(sum(y'*y))-sum(sum(sample.^2));
% r is divided into diagonal
% and off-diagonal terms, and the off-diagonal term
% is itself divided into smaller terms
rdiag=1/t*sum(sum(y.^2))-sum(diag(sample).^2);
z=x.*xmkt(:,ones(1,n));
v1=1/t*y'*z-covmkt(:,ones(1,n)).*sample;
roff1=sum(sum(v1.*covmkt(:,ones(1,n))'))/varmkt...
-sum(diag(v1).*covmkt)/varmkt;
v3=1/t*z'*z-varmkt*sample;
roff3=sum(sum(v3.*(covmkt*covmkt')))/varmkt^2 ...
-sum(diag(v3).*covmkt.^2)/varmkt^2;
roff=2*roff1-roff3;
r=rdiag+roff;
% compute shrinkage constant
k=(p-r)/c;
shrinkage=max(0,min(1,k/t))
else % use specified number
shrinkage = shrink;
end
% compute the estimator
sigma=shrinkage*prior+(1-shrinkage)*sample;
end
It's a Part of the Matlab code from Ledoit/Wolf (2003). I don't understand why the demeaning the returns before calculating the covariance? Is this Matlab specific? In my opinion, there is no need for demeaning returns before calculating with the cov-function. (The function does it on its own)
Thanks for help in advance!
I am using bin2mat function from matlab file exchange, for some reason it runs very slow. Is it possible to make it run faster or is there an alternative? I am trying: zC = bin2mat(s.X,s.Y,s.Z,xC,yC); I am not sure where it gets bogged down. I need to do this on point cloud data to calculate volume and such.
Here is the code:
function ZG = bin2mat(x,y,z,XI,YI,varargin)
% BIN2MAT - create a matrix from scattered data without interpolation
%
% ZG = BIN2MAT(X,Y,Z,XI,YI) - creates a grid from the data
% in the (usually) nonuniformily-spaced vectors (x,y,z)
% using grid-cell averaging (no interpolation). The grid
% dimensions are specified by the uniformily spaced vectors
% XI and YI (as produced by meshgrid).
%
% ZG = BIN2MAT(...,#FUN) - evaluates the function FUN for each
% cell in the specified grid (rather than using the default
% function, mean). If the function FUN returns non-scalar output,
% the output ZG will be a cell array.
%
% ZG = BIN2MAT(...,#FUN,ARG1,ARG2,...) provides aditional
% arguments which are passed to the function FUN.
%
% EXAMPLE
%
% %generate some scattered data
% [x,y,z]=peaks(150);
% ind=(rand(size(x))>0.9);
% xs=x(ind); ys=y(ind); zs=z(ind);
%
% %create a grid, use lower resolution if
% %no gaps are desired
% xi=min(xs):0.25:max(xs);
% yi=min(ys):0.25:max(ys);
% [XI,YI]=meshgrid(xi,yi);
%
% %calculate the mean and standard deviation
% %for each grid-cell using bin2mat
% Zm=bin2mat(xs,ys,zs,XI,YI); %mean
% Zs=bin2mat(xs,ys,zs,XI,YI,#std); %std
%
% %plot the results
% figure
% subplot(1,3,1);
% scatter(xs,ys,10,zs,'filled')
% axis image
% title('Scatter Data')
%
% subplot(1,3,2);
% pcolor(XI,YI,Zm)
% shading flat
% axis image
% title('Grid-cell Average')
%
% subplot(1,3,3);
% pcolor(XI,YI,Zs)
% shading flat
% axis image
% title('Grid-cell Std. Dev.')
%
% SEE also RESHAPE ACCUMARRAY FEVAL
% A. Stevens 3/10/2009
% astevens#usgs.gov
%check inputs
error(nargchk(5,inf,nargin,'struct'));
%make sure the vectors are column vectors
x = x(:);
y = y(:);
z = z(:);
if all(any(diff(cellfun(#length,{x,y,z}))));
error('Inputs x, y, and z must be the same size');
end
%process optional input
fun=#mean;
test=1;
if ~isempty(varargin)
fun=varargin{1};
if ~isa(fun,'function_handle');
fun=str2func(fun);
end
%test the function for non-scalar output
test = feval(fun,rand(5,1),varargin{2:end});
end
%grid nodes
xi=XI(1,:);
yi=YI(:,1);
[m,n]=size(XI);
%limit values to those within the specified grid
xmin=min(xi);
xmax=max(xi);
ymin=min(yi);
ymax=max(yi);
gind =(x>=xmin & x<=xmax & ...
y>=ymin & y<=ymax);
%find the indices for each x and y in the grid
[junk,xind] = histc(x(gind),xi);
[junk,yind] = histc(y(gind),yi);
%break the data into a cell for each grid node
blc_ind=accumarray([yind xind],z(gind),[m n],#(x){x},{NaN});
%evaluate the data in each grid using FUN
if numel(test)>1
ZG=cellfun(#(x)(feval(fun,x,varargin{2:end})),blc_ind,'uni',0);
else
ZG=cellfun(#(x)(feval(fun,x,varargin{2:end})),blc_ind);
end
It is slower on these two steps for one run it took:
ZG=cellfun(#(x)(feval(fun,x,varargin{2:end})),blc_ind); took 33 secs
blc_ind=accumarray([yind xind],z(gind),[m n],#(x){x},{NaN}); took 10 secs
You can change blc_ind = ... to
ZG=accumarray([yind xind],z(gind),[m n],#mean,NaN);
and delete other codes form here so the is no need to if numel(test)>1....
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.