Using tf() function in MATLAB - matlab

I'm trying to input this transfer function in matlab, but I can't figure out how because it has both positive and negative exponents.
If I do H = tf([1],[1 1 1 1],0.1,'variable','z^-1') I almost get it, but I can't figure out how to add the positive z to the bottom. I'm trying to use this H to plot the poles and zeros with pzmap(H).

To avoid negative exponents, we can multiply both the denominator and the numerator by z^3:
H = tf([1 0 0 0 0],[1 1 1 1 1],0.1,'variable','z')
Or divide its by z
H = tf([1],[1 1 1 1 1],0.1,'variable','z^-1')

You can create
z = tf('z', 0.1)
and then create any transfer function you want, e.g.
H = z / (1 + z + z^-1 + z^-2 + z^-3)
However, Matlab automatically adds additional pole-zero pairs at z=0, to make the transfer function H contain only z and no z^-1. Therefore, you will see multiple poles at z=0 instead of only one. Unfortunately I haven't found a solution to stop Matlab from doing that...

What you refer to as a transfer function is actually called DSP representation due to their implementation properties. In that every power of z is a unit delay. Hence, you have to use the filt. In this representation z terms should have nonpositive powers hence if you factor out one z from the denominator and cancel out you get
H = filt(1,[1,1,1,1,1])

Related

How can I code a contour integral representation of cosine?

I am pretty new to MATLAB computation and would appreciate any help on this. Firstly, I am trying to integrate a cosine function using the McLaurin expansion [cos(z) = 1 − (z^2)/2 + (z^4)/4 + ....] and lets say plotted over one cycle from 0 to 2π. This first integral (as seen in Figure 1) would serve as a "reference" or "contour" for what I want to do next.
Figure 1 - "The first integral representation"
Now, my next problem comes from writing in MATLAB cos(z) in
terms of an integral in the complex plane.
Figure 2 - "showing cos(z) as an integral in the complex plane"
Where I could choose an equi-sampled set of points 'sn' along the contour, from 'sL' to 'sU'
and separated by '∆s'. This is Euler’s method.
I am trying to write a code to numerically approximate the integral
along a suitable contour and plot the approximation against the
exact value of cos(z). I would like to do this twice - once for
z ∈ [0, 6π] and once for complex valued z in the range
z ∈ [0 + i, 6π + ]. Then to plot both the real and imaginary part of the
computed cos(z)
I am aware of the steps I am looking to implement which I'll bullet-point here.
Choose γ, SL, SU , N.
Step through z from z lower to z upper (use a different
number of steps (other than N) for this).
For each value of z compute cos z by stepping along the contour in
N discrete steps from SL to SU .
For each value of sn along the contour compute the integrand e^(sn-(z^2/4sn))/sqrt(sn) and add it to the rolling sum [I have attached figure 3 showing an image formula of the integrand if its not clear!] Figure 3 - "The exponential integrand I am looking to compute"
Now I will show what I have attempted in MATLAB!
% "Contour Integral Representation of Cosine"
% making 'z' a possible number such as pi
N = 10000000; % example number - meaning sample of steps
z_lower = 0;
z_upper = 6*pi;
%==========================%
z1 = linspace(z_lower,z_upper,N);
y = 1;
Sl = y - 10*1i;
sum = 0.0;
%==========================%
for z = linspace(z_lower,z_upper,N)
for Sn = linspace(Sl,Su,N)
sum = sum + ((exp(Sn) - (z.^2/4*Sn))/sqrt(Sn))*ds;
end
end
sum = sum*(sqrt(pi)/2*pi*1i);
plot(Sn,sum)
Edit1: Hiya, this figure will show what I am expecting - the numerical method to be not exactly the same as the "symbolic" integration lets say. In figure 4, the black cosine wave is the same as in figure 1 and the blue is the numerical integration method.Figure 4 - "End Result of what I expect to plot

Simulate a 2D point mass moving along y=x^2 in MATLAB

I have a mixed set of differential and algebraic equations for which I have found the analytical solution in MATLAB. It concerns a point mass moving along a 2D curve constrained by y=x^2.
How would I go about using an ode-solver in MATLAB (or something else if it's easier) to simulate the ball rolling over the curve? The animation I can do myself, I'm more concerned with finding the velocities, xd yd, for each consecutive step. That's where I kind of get lost.
These are the equations of motion which I've derived using Lagrange multipliers. Hence the lambda. The lambda is the reaction force. I can calculate the accelerations, xdd ydd, but I also need the velocities in the state if I want to properly simulate this, I assume.
% Symbolic functions
syms y x xd yd xdd ydd
syms m g lambda
% Parameters
A = [m 0 -2*x; 0 m 1; -2*x 1 0];
X = [xdd ydd lambda].';
b = [0 -m*g -2*xd^2].';
sol = A\b % these are the states stored in X
So if you work out your problem using the lagrancian you would get the following formula seen below (see https://physics.stackexchange.com/questions/47154/ball-rolling-in-a-parabolic-bowl). The k-value comes from y=kx^2 (can be 1 for your example).
So rewrite this in the following form.
Now you just use
ddx= Formula seen above..
x = x + dx *dt
dx = dx + ddx *dt
t = t + dt
y = k*x*x
You make a loop with a sufficient small dt, and update you x-position velocity and acceleration.
Now you need
to specify the following starting values -> x0 dx0 ddx0 and dt.
I hope this helped
Cheers:)

Matlab Convolution regarding the conv() function and length()/size() function

I'm kind've new to Matlab and stack overflow to begin with, so if I do something wrong outside of the guidelines, please don't hesitate to point it out. Thanks!
I have been trying to do convolution between two functions and I have been having a hard time trying to get it to work.
t=0:.01:10;
h=exp(-t);
x=zeros(size(t)); % When I used length(t), I would get an error that says in conv(), A and B must be vectors.
x(1)=2;
x(4)=5;
y=conv(h,x);
figure; subplot(3,1,1);plot(t,x); % The discrete function would not show (at x=1 and x=4)
subplot(3,1,2);plot(t,h);
subplot(3,1,3);plot(t,y(1:length(t))); %Nothing is plotted here when ran
I commented my issues with the code. I don't understand the difference of length and size in this case and how it would make a difference.
For the second comment, x=1 should have an amplitude of 2. While x=4 should have an amplitude of 5. When plotted, it only shows nothing in the locations specified but looks jumbled up at x=0. I'm assuming that's the reason why the convoluted plot won't be displayed.
The original problem statement is given if it helps to understand what I was thinking throughout.
Consider an input signal x(t) that consists of two delta functions at t = 1 and t = 4 with amplitudes A1 = 5 and A2 = 2, respectively, to a linear system with impulse response h that is an exponential pulse (h(t) = e ^−t ). Plot x(t), h(t) and the output of the linear system y(t) for t in the range of 0 to 10 using increments of 0.01. Use the MATLAB built-in function conv.
The initial question regarding size vs length
length yields a scalar that is equal to the largest dimension of the input. In the case of your array, the size is 1 x N, so length yields N.
size(t)
% 1 1001
length(t)
% 1001
If you pass a scalar (N) to ones, zeros, or a similar function, it will create a square matrix that is N x N. This results in the error that you see when using conv since conv does not accept matrix inputs.
size(ones(length(t)))
% 1001 1001
When you pass a vector to ones or zeros, the output will be that size so since size returns a vector (as shown above), the output is the same size (and a vector) so conv does not have any issues
size(ones(size(t)))
% 1 1001
If you want a vector, you need to explicitly specify the number of rows and columns. Also, in my opinion, it's better to use numel to the number of elements in a vector as it's less ambiguous than length
z = zeros(1, numel(t));
The second question regarding the convolution output:
First of all, the impulses that you create are at the first and fourth index of x and not at the locations where t = 1 and t = 4. Since you create t using a spacing of 0.01, t(1) actually corresponds to t = 0 and t(4) corresponds to t = 0.03
You instead want to use the value of t to specify where to put your impulses
x(t == 1) = 2;
x(t == 4) = 5;
Note that due to floating point errors, you may not have exactly t == 1 and t == 4 so you can use a small epsilon instead
x(abs(t - 1) < eps) = 2;
x(abs(t - 4) < eps) = 5;
Once we make this change, we get the expected scaled and shifted versions of the input function.

Is there an optimized vectorized function of the rectified linear function max(0,x) in MATLAB?

I was trying to get an vector optimized version of the linear rectifier. i.e. y = max(0,x). So what it should compute its element wise max of zero and x_i. I obviously implemented:
function [ y ] = rectSig( x )
%rectSig computes vector-wise rectified linear function
% computes y = [..., max(0,x_i), ...]
n=length(x);
y = zeros(1,n);
for i=1:1:length(x);
y(i) = max(0,x(i));
end
end
however, I know that looping like this in MATLAB is ill advised. So I was wondering if there was a better way to do this or if obviously matlab had its own implementation of a vectorized version of such a function? I always try to avoid loops if I can in matlab if there is a way to vectorize my code. It usually tends to speed things up.
Btw, I obviously tried googling it but didn't really get the result I expected...
The solution is as simple as
y = max(x,0);
This works for x being a column, row vector, matrix, higher dimensional matrix, etc. On the other hand
y = max(zeros(1,length(x)),x);
only works for x being a row vector. It fails when x is a column vector or matrix.
max accepts matrix inputs:
x = -5:5;
comparisonvector = zeros(size(x));
y = max(comparisonvector, x);
Returns:
y =
0 0 0 0 0 0 1 2 3 4 5

finding spectral radius of the jacobi iteration matrix

I am using Matlab to find the spectral radius of the Jacobi iteration matrix where A=[4 2 1;1 3 1;1 1 4].
I can't seem to input the correct commands to get the size of the error after 5 iterations. Can someone help me?
Here are a list of commands that I put into Matlab so far:
A=[4 2 1;1 3 1;1 1 4]
A =
4 2 1
1 3 1
1 1 4
D=diagonal(diagonal(A));L=(A,-1);U=(A,1);
b=([3 -1 4])
x0j=zeros([0 0 0]);
x=D\(-(U+L)*x0j+b);r=b-A*x %Jacobi iteration.
------------------------------------------------------------------------------
Error using *
Inputs must be 2-D, o enter code here r at least one input must be scalar.
To compute element wise TIMES, use TIMES (.*) instead.
The spectral radius of a matrix is the maximum of the modulus of its eigenvalues. It can be simply computed using max(abs(eig(·))).
However, as others have noticed, your whole code seems pretty mixed up and not actually valid Matlab code, so your problem is not really to compute the spectral radius, is it? The algorithm is very straightforward and easy to implement:
% diagonal part of A and rest
D = diag(diag(A));
R = A - D;
% iteration matrix and offset
T = - inv(D) * R;
C = inv(D) * b;
% spectral radius condition
rho = max(abs(eig(T)));
if rho >= 1
error('no convergence')
end
% initial guess
x = randn(size(b));
% iteration
while norm(A * x - b) > 1e-15
x = T * x + C;
end
Note that I used inv(D) to directly follow the description in Wikipedia, but the inverse of a diagonal matrix can be easily computed using diag(1 ./ diag(D)).
I don't really see why one would need to separate R into an upper and lower part. I suppose it has to do with numerical efficiency, but then, Matlab is a very efficient high-level language for matrix computations already. So actually there is no need to implement the Jacobi algorithm in it explicitly when you can simply write A \ b – except for educational purposes I guess.