Find phase components of complex number - matlab

I am plotting the behavior of reflectivity in laser structure.
Belows is my code:
for mm=1:10000
deltabetaL=10-(2*(mm-1)/1000);
kappaL=1;
L=10^-3;
alphalossL=0.1;
phi=0;
c=299792458;
neq=3.5;
v=c/neq;
gammaL=sqrt((kappaL^2)-(deltabetaL^2));
req=(-j*kappaL*exp(j*phi)*tanh(gammaL))/(gammaL+((alphalossL/2)+j*deltabetaL)*tanh(gammaL));
A=abs(req);
theta=-angle(req);
Qine(mm)=deltabetaL;
Qreq0(mm)=A^2;
Qtheta(mm)=theta;
end
plot(Qine,Qreq0);
figure(2)
plot(Qine,Qtheta);
I expected to have figures for the amplitude A^2 and the phase component theta of reflectivity as follows
https://drive.google.com/open?id=0Bx6bUTVOinyySW9BZ1dXblFtQWc
https://drive.google.com/open?id=0Bx6bUTVOinyyTTBJTHh6YjctZ0U
(Sorry. I cannot embed the image directly.)
The form of amplitude is similar to what I expected. However, about the phase, there is a big difference. So I thought the problem came from what I calculated phase component of complex number req.
Could anyone tell me how I can fix it?
Thank you !

There is no problem with your calculations. The author of the plot that you are trying to replicate set phase angle to be between [-0.5*pi, 1.5*pi]. Therefore, you need to adjust your theta accordingly.
Adding the following simple if-else statement into your loop seems working:
if theta < -0.5*pi
theta = theta + 2*pi;
end
plot(Qine,Qtheta)
Of course, you can come up with more efficient ways of doing this.

Related

I'm trying to plot a graph but matrix dimensions don't agree in matlab

So I'm trying to plot a graph and this is my code so far
T=10; %set the values given to us
t(1)=0;
delta=0.01;
mu=0.05;
sigma=linspace(0,1,10001); %set the spacing for sigma
v=zeros(length(sigma),T); %set the xeros
k=1;
for sigma=linspace(0.01,1,1000)
t(k)=k*delta;
eta=randn(1); %define eta
S(2)=1+mu*delta+sigma*sqrt(delta)*eta; %set S
S(T+1)=S(10)+mu*delta*S(10)+sigma*sqrt(delta)*eta*S(10);
end
t(10000)=1; %set the rounding error
plot (S,sigma) %plot the graph
xlabel 'S' %label the axis
ylabel 'sigma'
I've tried using . to satisfy inner matrix dimensions (for S) but this hasn't worked. I've been going round in circles for a while now and can't figure it out.
I've tried your code and analyzed the problem, and I have a few doubts about it. It would be so helpful to know what problem are you trying to solve. But, focusing on what we have, one of the things I've seen is about the iteration. It doesn´t make sense to me, you've used a for iteration structure with the sigma condition. That's ok, let's see step by step what's happening:
for sigma=linspace(0.01,1,1000)
t(k)=k*delta;
eta=randn(1); %define eta
S(2)=1+mu*delta+sigma*sqrt(delta)*eta; %set S
S(T+1)=S(10)+mu*delta*S(10)+sigma*sqrt(delta)*eta*S(10);
end
First of all, you can define t(k) of the iteration, as the value doesn´t change with it. Next, you've written S(2) and S(T+1), here, you're doing an iteration, that's correct, but you're overwriting the values over and over again each loop, so you're overwriting some values of a matrix S. About S, it could be helpful to preassign the expected size in memory, you can use:
S=zeros(i,j); % Being i and j, the matrix dimensions.
or simply, as some people like, declaring the variable (not necessary in Matlab):
S=[];
This depends on the problem you're solving. I really want to help you, but I need to know more about the problem. I don't know your working method or how you face your problems, but what I always do is solve it first in a piece of paper, or if it's a numerical problem of some kind and you can't solve it, then just sketch the ideas you have and check things like the coherence in matrix operations (related to matrix sizes), and those kind of things...
Hope I've been helpful, and have a nice day :)

3D Laplace Relaxation in MATLAB

I was able to write a MATLAB program that plots a 1D Laplace relaxation between two metal plates to find equilibrium potential using Jacobi method.
i will be honest, i am not completely sure that i understand what i did, but here is the relevant part of the code:
N=100;
V = zeros(N,N);
V(1,:)=-1;
V(N,:)=1;
for n=1:400
for i=2:99
for j=2:99
V(i,j)=(V(i-1,j)+V(i+1,j)+V(i,j+1)+V(i,j-1))*0.25;
end
end
end
and this is how it looks like:
I am wondering if it is possible to do something similar using the same method, but in 3D. I want to visualize something similar in 3D, a 3D potential... box.
I tried using a similar equation that i found in "Computational Physics. N. J. Giordano & H. Nakanishi, Eq.(5.8)" :
V(i,j,k) = [V(i+1,j,k) + V(i-1,j,k) + V(i,j+1,k) + V(i,j-1,k) + V(i,j,k+1) + V(i,j,k-1)] * (1/6);
and here is the new code that i have been trying to get to work:
N=10; % Used smaller number to reduce processing time.
V = zeros(N,N,N);
V(:,:,1)=-1; %i am using planes instead of axis as "Insulators"
V(:,:,N)=1;
for n=1:100
for i=2:99
for j=2:99
for k=2:99
V(i,j,k)=(V(i+1,j,k)+V(i-1,j,k)+V(i,j+1,k)+V(i,j-1,k)+V(i,j,k+1)+V(i,j,k-1))*(1/6);
end
end
end
end
And i am getting a Index exceeds matrix dimensions. in the line where V(i,j,k) is.
So again, I am trying to get something that is the 3D version of the 2D graph linked above. *Also, i would really appreciate if someone can explain a little bit (not the MATLAB part, but the math part) what is exactly that i am doing here with that equation, and what this could be used for?
Greatly appreciate the help.
Edit: i forgot to ask: how would you graph this 3D array?
You have defined N but are not using it during the process. Since you have values such as i-1 and j-1 you need to start from 2. And for you have values such as i+1 and j+1 you need to end by N-1. So a working code will look like this:
N=10; % Used smaller number to reduce processing time.
V = zeros(N,N,N);
V(:,:,1)=-1; %i am using planes instead of axis as "Insulators"
V(:,:,N)=1;
for n=1:1
for i=2:N-1
for j=2:N-1
for k=2:N-1
V(i,j,k)=(V(i+1,j,k)+V(i-1,j,k)+V(i,j+1,k)+V(i,j-1,k)+V(i,j,k+1)+V(i,j,k-1))*(1/6);
end
end
end
end
Also, the first for-loop seems to be doing nothing in this piece of code that you have provided.

Q on plotting function against t and trajectory in phase space(matlab)

I am very beginner for matlab and try to solve this question. But so far it is not successful. I have spent quite a time and I think I need some help. I would appreciate any help!!!
I need to plot v against time and trajectory of v and w in phase space. The whole question is below and my code for previous question connected to this question is also below. I can go with subplot(2,1,1) for the first graph and subplot(2,1,2) for the next graph. But I am not sure what I have to do other than this. I kind of found ode45 command. But not sure how to use it and if it is the right one to use here. I have tried to use ode45. But it shows many errors that I don't understand.....Please help me on this. Thanks a lot!
'Create a figure which contains two graphs, using subplot. In the first graph, plot the temporal evolution of the membrane potential v(t) against time t. In the second graph, plot the corresponding trajectory (v(t); w (t)) in (the so-called) phase space.'
% my code is below.
a=0.08;
b=3.6;
c=0.7;
T=2; % this can be any number
I_ext=20; % this can be any number
dt=0.01; % this can be any number
function [ v,w ] = fhnn( a,b,c,I_ext,T,dt)
v=zeros(1,numel(T/dt));
w=zeros(1,numel(T/dt));
for n=1:numel(T/dt)
v(n+1)=(v(n)-v(n)^3/3-w(n)+I_ext)*dt+v(n);
w(n+1)=a*(v(n)-b*w(n)+c)*dt+w(n);
end
I gather you have a differential equation and are trying to directly plot that. You might find a better approach would be to actually solve the equation if that is possible.
Either way, recognising that:
numel returns the length of an array and dT/dt is always a scalar so the length is always one.
fhnn is not used here.
You still need a vector t.
If what is in your for loop is correct, the following should work:
a=0.08; b=3.6; c=0.7; T=2; I_ext=20; dt=0.01;
t = 0:dt:T;
v = zeros(1,round(T/dt));
w = zeros(1,round(T/dt));
for n=1:round(T/dt)-1
v(n+1)=(v(n)-v(n)^3/3-w(n)+I_ext)*dt+v(n);
w(n+1)=a*(v(n)-b*w(n)+c)*dt+w(n);
end
subplot(2,1,1)
plot(t,v)
xlabel('t')
ylabel('v')
subplot(2,1,2)
plot(v,w)
xlabel('v')
ylabel('w')

Placing gaussian function at different points on mesh

I am looking to create a random distribution of gaussian curve shapes on a large mesh. I basically want to take this function :
Z = 0.3*exp(-5*(x.^2+y.^2))-0.1;
Z(Z<0)=0;
and be able to choose its location (in x & y coords), and have multiple plots.
So at the moment, I have this:
But I would like to have this generated:
Is there a reasonably simple way to do this? I have tried to play around with the code but I am afraid I'm not a mathematics, nor a MATLAB expert.
Any help would be much appreciated.
Look at this!
the way this works:
Generate random point
Check if point is closer than sigma
If its not, then create a gaussian there!
repeat until Ngaussians reached
code:
clear
n_gaussians=15;
gaussians=0;
sigma=1; % std
mindist=sigma; % if distance is smaller than this gaussians "collide"
[x,y]= meshgrid(-5:0.1:5,-5:0.1:5);
used=[];
Z=zeros(size(x));
while gaussians<n_gaussians
xm=(rand(1)-0.5)*10;
ym=(rand(1)-0.5)*10;
notvalid=0;
for ii=1:size(used,2)
% if we are too close to any point.
if norm([xm-used(1,ii),ym-used(2,ii)])<mindist
notvalid=1; % do not add this gauusian
end
end
if notvalid
continue
end
used(:,end+1)=[xm;ym];
Zaux = 0.3/sigma*exp(-5*((x-xm).^2+(y-ym).^2)/sigma.^2)-0.1;
Zaux(Zaux<0)=0;
Z=Z+Zaux;
gaussians=gaussians+1;
end
surf(x,y,Z);
axis equal

MATLAB Fitting Function

I am trying to fit a line to some data without using polyfit and polyval. I got some good help already on how to implement this and I have gotten it to work with a simple sin function. However, when applied to the function I am trying to fit, it does not work. Here is my code:
clear all
clc
lb=0.001; %lowerbound of data
ub=10; %upperbound of data
step=.1; %step-size through data
a=.03;
la=1482/120000; %1482 is speed of sound in water and 120kHz
ep1=.02;
ep2=.1;
x=lb:step:ub;
r_sq_des=0.90; %desired value of r^2 for the fit of data without noise present
i=1;
for x=lb:step:ub
G(i,1)= abs(sin((a/la)*pi*x*(sqrt(1+(1/x)^2)-1)));
N(i,1)=2*rand()-1;
Ghat(i,1)=(1+ep1*N(i,1))*G(i,1)+ep2*N(i,1);
r(i,1)=x;
i=i+1;
end
x=r;
y=G;
V=[x.^0];
Vfit=[x.^0];
for i=1:1:1000
V = [x.^i V];
c = V \ y;
Vfit = [x.^i Vfit];
yFit=Vfit*c;
plot(x,y,'o',x,yFit,'--')
drawnow
pause
end
The first two sections are just defining variables and the function. The second for loop is where I am making the fit. As you can see, I have it pause after every nth order in order to see the fit.
I changed your fit formula a bit, I got the same answers but quickly got
a warning that the matrix was singular. No sense in continuing past
the point that the inversion is singular.
Depending on what you are doing you can usually change out variables or change domains.
This doesn't do a lot better, but it seemed to help a little bit.
I increased the number of samples by a factor of 10 since the initial part of the curve
didn't look sampled highly enough.
I added a weighting variable but it is set to equal weight in the code below. Attempts
to deweight the tail didn't help as much as I hoped.
Probably not really a solution, but perhaps will help with a few more knobs/variables.
...
step=.01; %step-size through data
...
x=r;
y=G;
t=x.*sqrt(1+x.^(-2));
t=log(t);
V=[ t.^0];
w=ones(size(t));
for i=1:1:1000
% Trying to solve for value of c
% c that
% yhat = V*c approximates y
% or y = V*c
% V'*y = V'*V * c
% c = (V'*V) \ V'*y
V = [t.^i V];
c = (V'*diag(w.^2)*V ) \ (V'*diag(w.^2)*y) ;
yFit=V*c;
subplot(211)
plot(t,y,'o',t,yFit,'--')
subplot(212)
plot(x,y,'o',x,yFit,'--')
drawnow
pause
end
It looks like more of a frequency estimation problem, and trying to fit a unknown frequency
with polynomial tends to be touch and go. Replacing the polynomial basis with a quick
sin/cos basis didn't seem to do to bad.
V = [sin(t*i) cos(t*i) V];
Unless you specifically need a polynomial basis, you can apply your knowledge of the problem domain to find other potential basis functions for your fit, or to attempt to make the domain in which you are performing the fit more linear.
As dennis mentioned, a different set of basis functions might do better. However you can improve the polynomial fit with QR factorisation, rather than just \ to solve the matrix equation. It is a badly conditioned problem no matter what you do however, and using smooth basis functions wont allow you to accurately reproduce the sharp corners in the actual function.
clear all
close all
clc
lb=0.001; %lowerbound of data
ub=10; %upperbound of data
step=.1; %step-size through data
a=.03;
la=1482/120000; %1482 is speed of sound in water and 120kHz
ep1=.02;
ep2=.1;
x=logspace(log10(lb),log10(ub),100)';
r_sq_des=0.90; %desired value of r^2 for the fit of data without noise present
y=abs(sin(a/la*pi*x.*(sqrt(1+(1./x).^2)-1)));
N=2*rand(size(x))-1;
Ghat=(1+ep1*N).*y+ep2*N;
V=[x.^0];
xs=(lb:.01:ub)';
Vfit=[xs.^0];
for i=1:1:20%length(x)-1
V = [x.^i V];
Vfit = [xs.^i Vfit];
[Q,R]=qr(V,0);
c = R\(Q'*y);
yFit=Vfit*c;
plot(x,y,'o',xs,yFit)
axis([0 10 0 1])
drawnow
pause
end