I'm trying to use MATLAB to take exponentials of a matrix, and I would've expected that the output of this program would give a 2x2 matrix with cos(omega t) on the diagonals, and -i*sin(omega t) on the off diagonals. But instead I'm getting -sin(omega t) on the off diagonals, without any imaginary unit. Anybody have an idea where I'm going wrong here?
syms omega t
paulix = [ 0 1 ; 1 0 ];
U = expm(-1j*omega*t*paulix)
Related
I have some variables to find like x= [1x16 (x1,x2,x3,....x16 variables)] with condition that x1+x2+x3+....x16=1. I have also 16x16 matrix Q= [16x16 (real values)].
I need to solve the equation 'x*Q=x' as shown here. How can I solve it in Matlab or in any other language easily?
By transposition, your equation is equivalent to Q'y=1y where y:=x' (a column vector) where Q' is the transpose of Q (matlab notation...) which means that y is an eigenvector associated with eigenvalue 1 for matrix Q'. Such an eigenvector always exists for a Markov matrix. Let s be the sum of the entries of column vector y. Two cases can occur :
either s is not 0 ; then it suffices to divide all coordinates of y by s : we obtain a vector that is still an eigenvector, with a coordinate sum equal to 1.
or s=0 and there is no solution to your problem.
Here is a Matlab program that does the work for a 3 x 3 matrix :
M=[.2 .3 .5
.1 .8 .1
.4 .4 .2]
[P,D]=eig(M')
Y=P(:,3)
M'*Y - Y,% should be 0
Z=Y/sum(Y),%the sum of Z's coordinates is 1
M'*Z-Z,% should be 0
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.
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
I'm trying to solve a system of DAE (mixture of ODE and Algebraic Eq). So, my system looks like this
M dy/dt = F(t,y)
The matrix M is basically a constant mass matrix 1 in the diagonal with all zeros on the few last lines and few last column.
so for an example mass matrix looks like this
M = [1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 0]
my vector Fx is in dimension (4x1) if we take the matrix example.
How do I proceed if I get this error?
Matrix is singular, close to singular or badly scaled. Results may be inaccurate. RCOND = NaN
my code for the system resolution :
Mass = Mass_Matrix( Nc,NT );
opt = odeset('RelTol', 10.0^(-3), 'AbsTol' , 10.0^(-3), 'Mass', Mass ,'MassSingular', 'yes', 'OutputFcn',#odeprint);
[T,Y] = ode15s(#(t,y)Function_Fx( t, y, Resolution, y01),[0 1],y0,opt);
and my vector Fx is created by the Function_Fx
function Fx = Function_Fx( t, y, Resolution, y01)
With Resolution being a struct variables, and y01 a stored values.
My question is where could be the problem, is it the F(t,y) or the M? Given M is constant mass matrix.
Thank you for your help
I've solved this problem. It was because my F(t,y) is wrong. I checked the jacobian only by then I managed to see that I have some lines of zeros.
I am trying to solve the following optimization problem in octave
The first contraint is that A be positive semi-definite.
S is a set of data points such that if (xi,xj) is in S then xi is similar to xj and D is a set of data points such that if (xi,xj) is in D then xi and xj are dissimilar. Note that the above formula is 2 separate sums and the second sum is not nested. Also xi and xj are assumed to be column vectors of length N.
Because this is a nonlinear optimization I am trying to use octave's nonlinear program solver, sqp.
The problem is that if I just provide it with the function to optimize, on some small toy tests the, BFGS method to find the Hessian
fails. Because of this I tried to provide my own Hessian function but now this problem occurs
error: __qp__: operator *: nonconformant arguments (op1 is 2x2, op2 is 3x1)
error: called from:
error: /usr/share/octave/3.6.3/m/optimization/qp.m at line 393, column 26
error: /usr/share/octave/3.6.3/m/optimization/sqp.m at line 414, column 32
when I make the following call to sqp
[A, ~, Info] = sqp(initial_guess, {#toOpt, #CalculateGradient,#CalculateHessian},
[],[],0,[],maxiter);
I simplified the constraint that A be positive semi-definite and diagonal by only solving for the diagonal entries and constraining all the diagonal entries to be >=0. initial_guess is a vector of ones that is N long.
Here is my code to calculate what I believe to be the Hessian matrix
%Hessian = CalculateHessian(A)
%calculates the Hessian of the function we are optimizing as follows
%H(i,j) = (sumsq(D(:,i),1) * sumsq(D(:,j),1)) / (sum(A.*sumsq(D,1))^2)
%where D is a matrix of of differences between observations that are dissimilar, with one difference on each row
%and sumsq is the sum of the squares
%input A: the current guess for A
%output Hessian: The hessian of the function we are optimizing
function Hessian = CalculateHessian(A)
global HessianNumerator; %this is a matrix with the numerator of H(i,j)
global Dsum_of_squares; %the sum of the squares of the differences of each dimensions of the dissimilar observations
if(iscolumn(A)) %if A is a column vector
A = A'; %make it a row vector. necessary to prevent broadcasting
endif
if(~isempty(Dsum_of_squares)) %if disimilar constraints were provided
Hessian = HessianNumerator / (sum(A.*Dsum_of_squares)^2)
else
Hessian = HessianNumerator; %the hessian is a matrix of 0s
endif
endfunction
and Dsum_of_squares and HessianNumertor are
[dissimilarRow,dissimilarColumn] = find(D); %find which observations are dissimilar to each other
DissimilarDiffs = X(dissimilarRow,:) - X(dissimilarColumn,:); %take the difference between the dissimilar observations
Dsum_of_squares = sumsq(DissimilarDiffs,1);
HessianNumerator = Dsum_of_squares .* Dsum_of_squares'; %calculate the numerator of the Hessian. it is a constant value
X is a M x N matrix with one observation per row.
D is a M x M dissimilarity matrix. if D(i,j) is 1 then row i of X is dissimlar to row j. 0 otherwise.
I believe my error is in one of the following areas (from least likely to most likely)
The math I used to derive the Hessian function is wrong. The formula I am using is in my comments for the function.
My implementation of the math.
The Hessian Matrix that sqp wants is different from the one described on the Hessian Matrix Wikipedia page.
Any help would be greatly appreciated. If you need me to post more code I would be happy to do so. Right now the amount of code to try and solve the optimization is about 160 lines.
Here is the test case I am running that causes the code to fail. It works if I only pass it the gradient function.
X = [1 2 3;
4 5 6;
7 8 9;
10 11 12];
S = [0 1 1 0;
1 0 0 0;
1 0 0 0;
0 0 0 0]; %this means row 1 of X is similar to rows 2 and 3
D = [0 0 0 0;
0 0 0 0;
0 0 0 1;
0 0 1 0]; %this means row 3 of X is dissimilar to row 4
gml(X,S,D, 200); %200 is the maximum number of iterations for sqp to run