Using a simple Euler method to solve the EoS of Stars (Mathematica) - matlab

I attempted to translate a matlab code:
clear
clc;
%Use a resolution of dr = 10^-N
N = 4;
%G = GAMMA, adiabatic parameter
G = 4/3; % high density/extreme relativistic
%G = 5/3; % low density/nonrelativistic
r = 0;
dr = 10^-N;
m(1) = 0;
r(1) = 0;
rho(1) = 0.1;
i = 1;
while (i>0)
i=i+1;
r(i) = r(i-1)+dr;
Gamma(i) = rho(i-1)^(G-1) / (3*sqrt(2)) ;%(rho(i-1))^(2/3) / (3*(1+rho(i-1)^(2/3) )^(1/2) );
drho = (m(i-1)*rho(i-1)) / (Gamma(i) * r(i)^2)*dr;
if (drho > rho(i-1))
break;
else
rho(i) = rho(i-1) - drho;
end
m(i) = m(i-1) + (r(i)^2 * rho(i)) * dr;
end
Mass = m(i-1)
Rad = r(i-1)
plot(r(1:i-1),m(1:i-1))
xlabel('Log10(r/[m])')
ylabel('M(r) (M_{sol})')
Into Mathematica, what I have is:
EoS[n0_] :=
Module[{n = n0},
N1 = 4;
G1 = 4/3;
G2 = 5/3;
rho[n_] := 0.1 + n;
m1[n_] := n;
dr = 10^(-N1);
r[n_] := n;
Gamma1[n_] := ((rho[n - 1])^(G1 - 1))/(3*Sqrt[2]);
drho = ((m1[n - 1]*rho[n - 1]))/(Gamma1[n - 1]*r[n - 1]^2)*dr;
n = 1;
While[n > 0, Gamma1[n] && drho; n++]
If[drho > rho[-1], Break[], rho[n] = rho[-1] - drho]
m1[n] = m1[-1] + ((r[n]^2)*rho[n])*dr;
Mass = m1[n - 1];
Rad = r[n - 1];
ParametricPlot[{m[n], r[n]}, {n, 1, n - 1},
AxesLabel -> {"Log10(r/[m])", "M(r)(M_{sol})"}]
]
My problem is I'm getting complex solutions when I obviously shouldn't. I'm an absolute novice to mathematica, especially with modules and the euler method itself. Any and all feedback/help would be much appreciated. I'm assuming my increments are wrong, I don't really know.

Related

Secant Method not converging, Matlab

I have created a program in Matlab to try to find the root of f(x) = exp(2x) + 3x - 4 (the function "fopg1" in my code). My code is as follows:
format long
tic;
for dum=1:1000;
x(1) = 0.5;
x(2) = 0.4;
err_tol = 1e-8;
iteration(1) = 1;
n = 3;
while err_estimate > err_tol
iteration(n) = n;
x(n) = x(n-1) - fopg1(x(n-2)) * ((x(n-1) - x(n-2)) / (fopg1(x(n-1)) - fopg1(x(n-2))));
err_estimate(n) = abs(x(n) - x(n-1));
n = n + 1;
end
%end
time = toc;
avgtime = time/1000;
A = [iteration' x' err_estimate' tbd'];
f = '%2i %13.9f %13.9f %7.3f'; compose(f,A)
Unfortunately this does not converge. I feel like it should. Is there a flaw in my program or does it in fact not converge? Thanks in advance.
Maarten
I answered a very similar question here a few days ago. Using the same code, without an iterations limit and with an increased tolerance (1e-8 as per your example), I detect the expected convergence of exp(2x) + 3x - 4 using the secant method:
clear();
clc();
com = Inf;
i = 2;
err_tol = 1e-8;
f = #(x) exp(2*x) + 3*x - 4;
x(1) = 0.5;
x(2) = 0.4;
while (abs(com) > err_tol)
com = f(x(i)) * (x(i) - x(i-1)) / (f(x(i)) - f(x(i-1)));
x(i+1)= x(i) - com;
i = i + 1;
n = n - 1;
end
display(['Root X = ' num2str(x(end))]);
The message I receive is: Root X = 0.47369. It shouldn't be hard for you to implement your additional data within this code.

how to Improve the speed matlab

This is my matlab code. It runs too slow and I had no clue how to improve it.
Could you help me to improve the speed?
What I would like to do is to create some random points and then remove the random points to make them similar to my target points.
syms Dx Dy p q;
a = 0;
num = 10;
x = rand(1,num);
y = rand(1,num);
figure(1)
scatter(x,y,'.','g')
%num_x = xlsread('F:\bin\test_2');% num 1024
%figure(2)
%scatter(num_x(:,1),num_x(:,2),'.','r');
q = 0;
num_q = 10;
x_q = randn(1,num_q);
y_q = randn(1,num_q);
%figure(2)
hold on;
scatter(x_q,y_q,'.','r')
for i = 1:num_q;
for j = 1:num_q;
qx(i,j) = x_q(i) - x_q(j);
qy(i,j) = y_q(i) - y_q(j);
%qx(i,j) = num_x(i,1) - num_x(j,1);
%qy(i,j) = num_x(i,2) - num_x(j,2);
%d~(s(i),s(j))
if ((qx(i,j))^2+(qy(i,j)^2))> 0.01 % find neighbours
qx(i,j) = 0;
qy(i,j) = 0;
end
end
end
for i = 1:num_q;
for j = 1:num_q;
if qx(i,j)>0&&qy(i,j)>0
q = q + exp(-(((Dx - qx(i,j))^2)+((Dy - qy(i,j))^2))/4);%exp(-(((Dx - qx(i,j))^2)+((Dy - qy(i,j))^2))/4);
end
end
end
%I = ones(num,num); % I(s) should from a grayscale image
%r = 1./sqrt(I);
for s = 1:100;
for i = 1:num;
for j = 1:num;
dx(i,j) = x(i) - x(j);
dy(i,j) = y(i) - y(j);
%d~(s(i),s(j))
if ((dx(i,j))^2+(dy(i,j)^2))> 0.05 % delta p, find neighbours
dx(i,j) = 0;
dy(i,j) = 0;
end
end
end
p = 0;
for i = 1:num;
for j = 1:num;
if dx(i,j)>0&&dy(i,j)>0
p = p + exp(-(((Dx - dx(i,j))^2)+((Dy - dy(i,j))^2))/4);
end
end
end
p = p - q;
sum = 0;
for i = 1:num;
for j = 1:num;
if dx(i,j)>0&&dy(i,j)>0;
kx(i,j) = (1/2)*(Dx-dx(i,j))*exp((-(Dx-dx(i,j))^2+(Dy-dy(i,j))^2)/4);
ky(i,j) = (1/2)*(Dy-dy(i,j))*exp((-(Dx-dx(i,j))^2+(Dy-dy(i,j))^2)/4);
end
end
end
sum_x = ones(1,num);% 1行N列0矩阵
sum_y = ones(1,num);
%fx = zeros(1,num);
for i = 1:num;
for j = 1:num;
if dx(i,j)>0&&dy(i,j)>0;
fx(i) = p*kx(i,j);% j is neighbour to i
fy(i) = p*ky(i,j);
%fx(i) = matlabFunction(fx(i));
%fy(i) = matlabFunction(fy(i));
%P =quad2d(#(Dx,Dy) fx,0,0.01,0,0.01);
%fx =quad(#(Dx) fx,0,0.01);
%fx(i) =quad(#(Dy) fx(i),0,0.01);
%Q =quad2d(#(Dx,Dy) fy,0,0.01,0,0.01);
fx(i) = double(int(int(fx(i),Dx,0,0.01),Dy,0,0.01));
fy(i) = double(int(int(fy(i),Dx,0,0.01),Dy,0,0.01));
%fx(i) = vpa(p*kx(i,j));
%fy(i) = vpa(p*ky(i,j));
%fx(i) = dblquad(#(Dx,Dy)fx(i),0,0.01,0,0.01);
%fy(i) = dblquad(#(Dx,Dy)fy(i),0,0.01,0,0.01);
sum_x(i) = sum_x(i) + fx(i);
sum_y(i) = sum_y(i) + fy(i);
end
end
end
for i = 1:num;
sum_x = 4.*sum_x./num;
sum_y = 4.*sum_y./num;
x(i) = x(i) - 0.05*sum_x(i);
y(i) = y(i) - 0.05*sum_y(i);
end
a = a+1
end
hold on;
scatter(x,y,'.','b')
The fast version of your loop should be something like:
qx = bsxfun(#minus, x_q.', x_q);
qy = bsxfun(#minus, y_q.', y_q);
il = (qx.^2 + qy.^2 >= 0.01);
qx(il) = 0;
qy(il) = 0;
il = qx>0 && qy>0;
q = sum(exp(-((Dx-qx(il)).^2 + (Dy-qy(il)).^2)/4));
%// etc. for vectorization of the inner loops

Plotting iteratively defined function in MATLAB

I'm not a MATLAB professional and so, I need some help at producing a 3D plot of the iteratively defined function f : R^2-0 -> R defined below (in pseudocode) for x,y values in [-1,1] and
For each I = 1,2,3 and A = (0.5,0.5)
function f(v in R^2-0)
{
a=b=0; (a,b in R)
for (i=0; i<I; i=i+1)
{
v = |v| / ||v||^2 - A;
a = a + | ||v||-b |;
b = ||v||;
}
return a;
}
(|v| denotes component-wise vector absolute value)
(If you want you can look at the fractal that is generated by the function at my question on math-exchange here:
https://math.stackexchange.com/questions/1457733/a-question-about-a-fractal-like-iteratively-defined-function
)
MATLAB code to do that will be appreciated.
Much Thanks.
Save this your main program:
clear
clc
close all
% I = 1;
% A = [ 0.5 0.5 ];
I = 10;
A = [ 0.5 0.5 0.5 ];
xmin = -1;
xmax = 1;
ymin = -1;
ymax = 1;
nx = 101;
ny = 101;
dx = (xmax - xmin) / (nx - 1);
dy = (ymax - ymin) / (ny - 1);
x = xmin: dx: xmax;
y = ymin: dy: ymax;
for ix = 1: nx
for iy = 1: ny
if (length(A) == 2)
z(iy, ix) = f([x(ix) y(iy)], A, I);
elseif (length(A) == 3)
z(iy, ix) = f([x(ix) y(iy) 0], A, I);
end
end
end
pcolor(x, y, z)
shading interp
Then save this function in the same directory as the main program as f.m:
function result = f(v, A, I)
a = 0;
b = 0;
for i = 1: I
v = abs(v) / dot(v, v) - A;
a = a + abs(norm(v) - b);
b = norm(v);
end
result = a;
end

How to Run a Script for 30 - 40 Values with Increasing Magnitude

I would like to run the following for 30 to 40 values of the current (I0) with increasing magnitude. Can someone please tell me how to make this happen?
GNa = 400;
GK = 200;
GL = 2;
ENa = 99;
EK = -85;
VL = -65;
C = 2;
dt = .01;
t = 0:dt:200;
I0 = 200;
It= I0 + 0*t;
It(1:40/dt)=0;
m = zeros(1,length(t));
n = zeros(1,length(t));
h = zeros(1,length(t));
V = zeros(1,length(t));
V(1) = -65;
am = zeros(1,length(t));
bm = zeros(1,length(t));
an = zeros(1,length(t));
bn = zeros(1,length(t));
ah = zeros(1,length(t));
bh = zeros(1,length(t));
for i=1:length(t)-1
I=It(i);
am(i) = (0.1*(V(i) + 40))/(1 - exp(-0.1*(V(i)+40)));
bm(i) = 4*exp(-0.0556*(V(i)+65));
ah(i) = 0.07*exp(-0.05*(V(i)+65));
bh(i) = 1./(1+exp(-0.1*(V(i)+35)));
an(i) = (0.01*(V(i)+55))/(1 - exp(-0.1*(V(i)+55)));
bn(i) = 0.125*exp(-0.0125*(V(i)+65));
m(i+1) = m(i) + dt*(am(i)*(1 - m(i)) - bm(i)*m(i));
h(i+1) = h(i) + dt*(ah(i)*(1 - h(i)) - bh(i)*h(i));
n(i+1) = n(i) + dt*(an(i)*(1 - n(i)) - bn(i)*n(i));
V(i+1) = V(i) + dt*(((-GL*(V(i) - VL) - GNa*(m(i).^3)*h(i)*(V(i) - ENa) - GK* (n(i).^4)*(V(i) - EK)+ I))/C);
end
You can always wrap this in another for loop, no?
I0list = 200:2.5:300 % 41 values including endpoints
for j = 1:length(IOlist)
I0 = IOlist(j);
% Rest of your code, minus setting I0, goes here
end
If you need to store all of the values, make m etc. be m = zeros(length(IOlist),length(t)); instead, and then use both indices when assigning, e.g.
am(j,i) = ...

Perform step-by-step integral

I have this piece of code:
time = 614.4;
Uhub = 11;
HubHt = 90;
TI = 'A';
N1 = 4096;
N2 = 32;
N3 = 32;
L1 = Uhub*time;
L2 = 150;
L3 = 220;
V = L1*L2*L3;
gamma = 3.9;
c = 1.476;
b = 5.6;
if HubHt < 60
lambda1 = 0.7*HubHt;
else
lambda1 = 42;
end
L = 0.8*lambda1;
if isequal(TI,'A')
Iref = 0.16;
sigma1 = Iref*(0.75*Uhub + b);
elseif isequal(TI,'B')
Iref = 0.14;
sigma1 = Iref*(0.75*Uhub + b);
elseif isequal(TI,'C')
Iref = 0.12;
sigma1 = Iref*(0.75*Uhub + b);
else
sigma1 = str2num(TI)*Uhub/100;
end
sigma_iso = 0.55*sigma1;
%% Wave number vectors
ik1 = cat(2,(-N1/2:-1/2),(1/2:N1/2));
ik2 = -N2/2:N2/2-1;
ik3 = -N3/2:N3/2-1;
[x y z] = ndgrid(ik1,ik2,ik3);
k1 = reshape((2*pi*L/L1)*x,N1*N2*N3,1);
k2 = reshape((2*pi*L/L2)*y,N1*N2*N3,1);
k3 = reshape((2*pi*L/L3)*z,N1*N2*N3,1);
k = sqrt(k1.^2 + k2.^2 + k3.^2);
Now I should calculate
where
The procedure to calculate the integral is
At the moment I'm using this loop
E = #(k) (1.453*k.^4)./((1 + k.^2).^(17/6));
E_int = zeros(1,N1*N2*N3);
E_int(1) = 1.5;
for i = 2:(N1*N2*N3)
E_int(i) = E_int(i) + quad(E,i-1,i);
end
neglecting for the k>400 approximation. I believe that my loop is not right.
How would you suggest to calculate the integral?
I thank you in advance.
WKR,
Francesco
This is a list of correction from the more obvious to the possibly more subtle. (Indeed I start from what you wrote in the final part going upwards).
From what you write:
E = #(k) (1.453*k.^4)./((1 + k.^2).^(17/6));
E_int = zeros(1,N1*N2*N3);
E_int(1) = 1.5;
for i = 2:(N1*N2*N3)
%//No point in doing this:
%//E_int(i) = E_int(i) + quad(E,i-1,i);
%//According to what you write, it should be:
E_int(i) = E_int(i-1) + quad(E,i-1,i);
end
You could speed the whole thing up by doing
%//Independent integration on segments
Local_int = arrayfun(#(i)quad(E,i-1,i), 2:(N1*N2*N3));
Local_int = [1.5 Local_int];
%//integral additivity
E_int = cumsum(Local_int);
Moreover, if the known condition (point 2.) really is "... ( = 1.5 if k' = 0)", then the whole implementation should really be more like
%//Independent integration on segments
Local_int = arrayfun(#(i)quad(E,i-1,i), 2:(N1*N2*N3));
%//integral additivity + cumulative removal of queues
E_int = 1.5 - [0 fliplr(cumsum(fliplr(Local_int)))]; %//To remove queues