Hessenberg matrix with householder transformation on Hermitian matrix - matlab

I have written a program to find a Hessenberg matrix who's orthogonal equivalent with a matrix A using householder transformations. The program works fine until I start using Hermitian matrices. Normally, when using hermitian matrices, the hessenberg matrix should be tridiagonal but mine only has zeros at some places of the first row (and of course below the subdiagonal). Can anyone help me?
My householder function is defined as:
function [H,Q]=householder(A)
[m,n] = size(A);
Q=eye(n);
for k = 1:n-2
x=A(k+1:n,k);
[sz,szz] = size(x);
e_k = zeros(sz,1);
e_k(1)=1;
u = (x+sign(x(1))*norm(x)*e_k)/(norm(x+sign(x(1))*norm(x)*e_k));
I=eye(sz);
P=I-2*(u)*(u');
Q_temp=blkdiag(eye(k),P);
Q=Q_temp*Q;
A=(Q_temp')*A*(Q_temp);
end
H=A;
end
I make a random Hermitian matrix:
function RHM=RandomHermitianMatrix(n)
A=complex(rand(n,n),(rand(n,n)*2)-1);
for k=1:n-1
vct=diag(A,k);
for l=1:n-k
A(l+k,l)=conj(vct(l));
end
end
RHM=A;
end
I test it using:
function message = test_householder_hermitian(n)
tic;
tst=RandomHermitianMatrix(n)
tstt=householder(tst)
toc
message='done';
end
Thanks a lot!

Related

Problem in 2D heat equation solution using FDM in Matlab

I am trying to solve the 2D time dependent heat equation using finite difference method in Matlab. The code is below:
%Spatial variable on x direction
Lx=1;
delta=0.1;
xmin=-Lx/2;
xmax=Lx/2;
Nx=(xmax-xmin)/delta;
x=linspace(xmin,xmax,Nx);
%Spatial variable on y direction
Ly=1;
delta=0.1;
ymin=-Ly/2;
ymax=Ly/2;
Ny=(ymax-ymin)/delta;
y=linspace(ymin,ymax,Ny);
%Total matrix size
N = (Nx * Ny);
%Time variable
dt=0.002;
tmin=0;
tmax=1;
nt=(tmax-tmin)/dt;
tspan=linspace(tmin,tmax,nt);
%Create a meshgrid
[X,Y] = meshgrid(x,y);
% Defining initial state:
T0=exp(-(X.^2+Y.^2));
%reshape the initial condition to a vector
T_reshape = reshape(T0,N,1);
% Constructing the 1D spatial matrix
A=zeros(N,N);
I = eye(N);
%the diagonal elements
for m=1:N %the number of rows
for n=1:N %the number of columns
if (m==n)
A(m,n)=-2/delta^2;
end
%Boundary conditions: A(1,N)==A(N,1)
if(n==N)&&(m==1)
A(m,n)=1;
end
if(n==1)&&(m==N)
A(m,n)=1;
end
end
end
%the off-diagonal elements
for n=1:N-1
A(n+1,n)=1/delta^2; %the value of each lower off-diagonal elements
end
for n=2:N
A(n-1,n)=1/delta^2; %the value of each upper off-diagonal element
end
%create the 2D matrix
B = kron(A,I)+kron(I,A);
% Solve the equation
[Time,Tem]=ode45('dTDistribution',tspan,T_reshape,[],B,delta);
The function that is being called here is as following:
%Define the function
function dT=dTDistribution(tspan,T_reshape,dummy,B,delta)
dT = B.*T_reshape;
end
My problem is that the dimension of my matrix B is different than the dimensions of the initial condition T_reshape, therefore, the multiplication of B.*T_reshape won't be possible. I'm wondering how can I change the dimension of T_reshape to make the multiplication valid. Hope anyone could help.
Thank you.
Thank you for looking at my problem, but I have figured out the mistake in the code. Since A is the 1D matrix, then its size should be either (Nx,Nx) or (Ny,Ny) and then when taking the tensor product to get B the 2D matrix its size will be (N,N). However in the code, A has the size of (N,N) and as a result B is blowing up making the multiplication afterwards not possible.
Thanks.

Matlab: Fourier coefficients

I have a problem with my code. My objective is to obtain the Fourier coefficients with the passage matrices. Then use the fft and check that my two results are the same. But I get different results and I don't understand why?
clear all;
N=[50];
for k=1:length(N)
Dx=1/(N(k)-1);
x=linspace(0,1-Dx,N(k));
for j=1:N(k)
f(j,k)=100.*exp(-20*x(j))*(x(j)-(x(j)).^2);
end
for j=1:N(k)
for m=1:N(k)
Mphsp(j,m)=exp((2*pi*i*(m-1)*(j-1))/N(k));
Mspph(j,m)=(1/N(k)).*exp(-(2*pi*i*(m-1)*(j-1))/N(k));
end
end
Idd=Mphsp*Mspph;
coeff(1:N(k),k)=Mspph*f(1:N(k),k);
coeff2(1:N(k),k)=fft(f(1:N(k),k));
verf(1:N(k),k)=coeff2(1:N(k),k)-coeff(1:N(k),k);
end
If anyone has any ideas? Please.
Your for loop is wrong. length(N) = 1, because N is a 1x1 matrix.
clear all;
N=[50];
for k=1:length(N)
I suppose you want to do something like
N = zeros(50, 1);
for k = 1:50
N(k) = k;
end
for k=1:length(N)
...

Matlab: merging a new script with inbuilt code to compare the execution time

Please, I have this code for determinant that runs but does not display the output only the time it does display. Can gurus in the house help me out.
function determ=calll(A)
A=input('rand()');
[rows, columns] = size(A);
tic;
if rows==2:size(A);
for m11=A(2:end,2:end);
m1n=A(2:end,1:end-1);
mn1=A(1:end-1,2:end);
mnn=A(1:end-1,1:end-1);
m11nn=A(1:end-2,1:end-2);
deter=(m11)*(mnn)-((m1n)*(mn1));
determ=deter./deternew(m11nn);
end
end
toc
disp('determinant =')
The real issue is that
I want to incorporate random matrix in the code so that when I run it, a random matrix will be used only just for me to specify the order of the matrix because I can not input 1000 by 1000 matrix manually.
An inbuilt Matlab code for determinant should also be embedded in my script.
Time of execution should be included for my code and for the inbuilt Matlab code.
In all, when I run the program, it should ask for the order (since a random matrix must be used) and compute the determinant using this code and the inbuilt Matlab code concurrently. Note that the determinant of this code and Matlab will be the same but their time of execution will be different. So my output after execution should be in two forms
the value of the determinant of my script and the time taken for the execution
the value of the determinant of the inbuilt Matlab method and the time taken for the execution.
#EBH
function out = thanksEBH
A = input('matrix A =');
[rows, columns] = size(A);
N=100;
t = zeros(N,1);
for k = 1:N
end
tic;
out=1;
for i = 1:rows
out = prod(A(i,i)*A(i,end));
end
t(k,1) = toc;
for i = 1:rows
out = prod(A(i,end-1)*A(end,i));
end
t(k,2) = toc;
t(k) = toc;
I really don't understand the purpose of this second code, but as far as I can guess what you try to do, I can suggest this:
function out = thanksEBH
n = input('matrix A =');
A = rand(n);
N = 100;
t = zeros(N,1);
out = 1;
for k = 1:N
tic
% first procedure to measure run-time
for i = 1:n
out = prod(A(i,i)*A(i,end));
end
t(k,1) = toc;
tic
% second procedure to measure run-time
for i = 1:n
out = prod(A(i,end-1)*A(end,i));
end
t(k,2) = toc;
end
disp(mean(t))
end
This will measure execution time of the two inner for loops separately and will display the mean of them. Anything you put inside the inner for loops will be measured. Note that I also changed the start of the function (among some other things) so it could run.
Please, if you have any other questions regarding this, ask them separately in a different question.
Well, I'm not a guru in matlab but I will to try to answer you:
For creating random arrays:
http://es.mathworks.com/help/matlab/math/create-arrays-of-random-numbers.html
In order to calulate the determinat in matlab you ca use the function det
function det
The easy way for get execution time in matlab is using the pair functions tic and toc
tic
A = rand(12000, 4400);
B = rand(12000, 4400);
toc
C = A'.*B';
toc
tic and toc
You can ask the user with the input command:
http://es.mathworks.com/help/matlab/ref/input.html
prompt = 'What is the original value? ';
x = input(prompt)
y = x*10
simply googling for a recursive determinant algorithm:
% The derminant of a matrix can be evaluated using a recursive formula such
% that: Assuming a square matrix A of order n
% det(A)=sum(a1j*Cj), for j=1,n
% where a1j represent the elements of the 1st row of the matrix A, and
% Cj is the determinant of the reduced matrix obtained removing the 1st row
% and the column j of the matrix A
function DetA=determin(A)
% This method can be applied for any nxn square matrix;
% Check Input Argument
if isempty(A)
error('cof:EmptyMatrix','The matrix A does not exist');
end
[r, c]=size(A); % number of rows and columns of A
if r~=c
error('det:NotSquareMatrix','The matrix A is not square');
end
DetA=0;
% Calculate determinant
if r==2,
% if the matrix a 2x2 matrix, then directly calculate the determinant
% using the common formula
DetA=A(1,1)*A(2,2)-A(1,2)*A(2,1);
else
% if the matrix is not 2x2 reduce its order of 1, generating a matrix
% with r-1 rows and c-1 columns. Subsequently recall the function using
% the reduced matrix
temp_A=A;
for i=1:c
a1i=temp_A(1,i); % save the element of the 1st row and ith column of the temporary matrix; this element will be used to calculate the determinant later on
if a1i~=0
temp_A(1,:)=[]; % remove the first row to create the reduced matrix
temp_A(:,i)=[]; % remove the ith column to create the reduced matrix
Cj=temp_A;
DetCj=determin(Cj); % Calculate the determinant of the reduced matrix recalling the function
DetA=DetA+((-1)^(1+i))*a1i*DetCj;
temp_A=A; % reset elements of temporary matrix to input elemens
end
end
end

Unexpected result with DFT in MATLAB

I have a problem when calculate discrete Fourier transform in MATLAB, apparently get the right result but when plot the amplitude of the frequencies obtained you can see values very close to zero which should be exactly zero. I use my own implementation:
function [y] = Discrete_Fourier_Transform(x)
N=length(x);
y=zeros(1,N);
for k = 1:N
for n = 1:N
y(k) = y(k) + x(n)*exp( -1j*2*pi*(n-1)*(k-1)/N );
end;
end;
end
I know it's better to use fft of MATLAB, but I need to use my own implementation as it is for college.
The code I used to generate the square wave:
x = [ones(1,8), -ones(1,8)];
for i=1:63
x = [x, ones(1,8), -ones(1,8)];
end
MATLAB version: R2013a(8.1.0.604) 64 bits
I have tried everything that has happened to me but I do not have much experience using MATLAB and I have not found information relevant to this issue in forums. I hope someone can help me.
Thanks in advance.
This will be a numerical problem. The values are in the range of 1e-15, while the DFT of your signal has values in the range of 1e+02. Most likely this won't lead to any errors when doing further processing. You can calculate the total squared error between your DFT and the MATLAB fft function by
y = fft(x);
yh = Discrete_Fourier_Transform(x);
sum(abs(yh - y).^2)
ans =
3.1327e-20
which is basically zero. I would therefore conclude: your DFT function works just fine.
Just one small remark: You can easily vectorize the DFT.
n = 0:1:N-1;
k = 0:1:N-1;
y = exp(-1j*2*pi/N * n'*k) * x(:);
With n'*k you create a matrix with all combinations of n and k. You then take the exp(...) of each of those matrix elements. With x(:) you make sure x is a column vector, so you can do the matrix multiplication (...)*x which automatically sums over all k's. Actually, I just notice, this is exactly the well-known matrix form of the DFT.

Bivariate mvncdf for a matrix with different covariance matrices (Matlab)

I want to do the following:
for i = 1:N
l(i) = mvncdf(x(i,:), mu, sigma(:,:,i))
end
Can I do it without a loop given that a covariance matrix is different for each row of x?
Sure. Try this:
func = #(i) mvncdf(x(i,:), mu, sigma(:,:,i));
l = arrayfun(func, 1:N)
This is a neat puzzle-type question, but I'd say that your code with a loop is much more readable and probably just as fast.