Animating 3D Random Walk Matlab - matlab

I am writing a code to simulate random walk in 3D space on Matlab. However, there seems to be a problem with my number of simulations, M. I want to animate multiple simulations on the same graph but I am only get 1 simulation. My input of M instead becomes the number of steps. How can I fix this code? Thank you.
I want it to look like the animation in this video: https://www.youtube.com/watch?v=7A83lXbs6Ik
But after each simulation is complete, another one starts on the same graph but a different color.
The end result should be like this
final
clc;
clearvars;
N = input('Enter the number of steps in a single run: '); % Length of the x-axis and random walk.
M = input('Enter the number of simulation runs to do: '); % The number of random walks.
x_t(1) = 0;
y_t(1) = 0;
z_t(1) = 0;
for m=1:M
for n = 1:N % Looping all values of N into x_t(n).
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
x_t(n+1) = x_t(n) + A;
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
y_t(n+1) = y_t(n) + A;
A = sign(randn);
z_t(n+1) = z_t(n) + A;
end
plot3([x_t(1) x_t(n+1)], [y_t(1) y_t(n+1)], [z_t(1) z_t(n+1)], 'g');
hold on
grid on
x_t = x_t(n+1);
y_t = y_t(n+1);
z_t = z_t(n+1);
drawnow;
end

You are plotting in the wrong place:
clc;
clearvars;
N = 100
M = 5
x_t(1) = 0;
y_t(1) = 0;
z_t(1) = 0;
c=lines(M) % save colors so each m has its own
for m=1:M
for n = 1:N % Looping all values of N into x_t(n).
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
x_t(n+1) = x_t(n) + A;
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
y_t(n+1) = y_t(n) + A;
A = sign(randn);
z_t(n+1) = z_t(n) + A;
plot3([x_t(n) x_t(n+1)], [y_t(n) y_t(n+1)], [z_t(n) z_t(n+1)],'color',c(m,:));
hold on
grid on
drawnow;
end
end

Related

Looping my algorithm to plot for a different parameter value on the same graph(MATLAB)

I've implemented an algorithm for my physics project which does exactly what I want. The problem that I'm stuck which is not the Physics content itself hence I think it might be somewhat trivial to explain what my code does. I'm mainly stuck with the way MATLAB's plotting works if I was to loop over the same algorithm to produce similar graphs with a slight change of a value of my parameter. Here's my code below:
clear; clc; close all;
% Parameters:
z_nn = 4; % Number of nearest-neighbour in lattice (square = 4).
z_nnn = 4; % Number of next-nearest-neighbours in lattice (square = 4).
Lx = 40; % Number of sites along x-axis.
Ly = 40; % Number of sites along y-axis.
sigma = 1; % Size of a site (defines our units of length).
beta = 1.2; % Inverse temperature beta*epsilon.
mu = -2.53; % Chemical potential mu/epsilon.
mu_2 = -2.67; % Chemical potential mu/epsilon for 2nd line.
J = linspace(1, 11, 11);%J points for the line graph plot
potential = zeros(Ly);
attract = 1.6; %wall attraction constant
k = 1; %wall depth
rho_0 = 0.4; % Initial density.
tol = 1e-12; % Convergence tolerance.
count = 30000; % Upper limit for iterations.
alpha = 0.01; % Mixing parameter.
conv = 1; cnt = 1; % Convergence value and counter.
rho = rho_0*ones(Ly); % Initialise rho to the starting guess(i-th rho_old) in Eq(47)
rho_rhs = zeros(Ly); % Initialise rho_new to zeros.
% Solve equations iteratively:
while conv>=tol && cnt<count
cnt = cnt + 1; % Increment counter.
% Loop over all lattice sites:
for j=1:Ly
%Defining the Lennard-Jones potential
if j<k
potential(j) = 1000000000;
else
potential(j) = -attract*(j-k)^(-3);
end
% Handle the periodic boundaries for x and y:
%left = mod((i-1)-1,Lx) + 1; % i-1, maps 0 to Lx.
%right = mod((i+1)-1,Lx) + 1; % i+1, maps Lx+1 to 1.
if j<k+1 %depth of wall
rho_rhs(j) = 0;
rho(j) = 0;
elseif j<(20+k)
rho_rhs(j) = (1 - rho(j))*exp((beta*((3/2)*rho(j-1) + (3/2)*rho(j+1) + 2*rho(j) + mu) - potential(j)));
else
rho_rhs(j) = rho_rhs(j-1);
end
end
conv = sum(sum((rho - rho_rhs).^2)); % Convergence value is the sum of the differences between new and current solution.
rho = alpha*rho_rhs + (1 - alpha)*rho; % Mix the new and current solutions for next iteration.
end
% disp(['conv = ' num2str(conv_2) ' cnt = ' num2str(cnt)]); % Display final answer.
% figure(2);
% pcolor(rho_2);
figure(1);
plot(J, rho(1:11));
hold on;
% plot(J, rho_2(1,1:11));
hold off;
disp(['conv = ' num2str(conv) ' cnt = ' num2str(cnt)]); % Display final answer.
figure(3);
pcolor(rho);
Running this code should give you a graph like this
Now I want to produce a similar graph but with one of the variable's value changed and plotted on the same graph. My approach that I've tried is below:
clear; clc; close all;
% Parameters:
z_nn = 4; % Number of nearest-neighbour in lattice (square = 4).
z_nnn = 4; % Number of next-nearest-neighbours in lattice (square = 4).
Lx = 40; % Number of sites along x-axis.
Ly = 40; % Number of sites along y-axis.
sigma = 1; % Size of a site (defines our units of length).
beta = 1.2; % Inverse temperature beta*epsilon.
mu = [-2.53,-2.67]; % Chemical potential mu/epsilon.
mu_2 = -2.67; % Chemical potential mu/epsilon for 2nd line.
J = linspace(1, 10, 10);%J points for the line graph plot
potential = zeros(Ly, length(mu));
gamma = zeros(Ly, length(mu));
attract = 1.6; %wall attraction constant
k = 1; %wall depth
rho_0 = 0.4; % Initial density.
tol = 1e-12; % Convergence tolerance.
count = 30000; % Upper limit for iterations.
alpha = 0.01; % Mixing parameter.
conv = 1; cnt = 1; % Convergence value and counter.
rho = rho_0*[Ly,length(mu)]; % Initialise rho to the starting guess(i-th rho_old) in Eq(47)
rho_rhs = zeros(Ly,length(mu)); % Initialise rho_new to zeros.
figure(3);
hold on;
% Solve equations iteratively:
while conv>=tol && cnt<count
cnt = cnt + 1; % Increment counter.
% Loop over all lattice sites:
for j=1:Ly
for i=1:length(mu)
y = 1:Ly;
MU = mu(i).*ones(Ly)
%Defining the Lennard-Jones potential
if j<k
potential(j) = 1000000000;
else
potential(j) = -attract*(j-k).^(-3);
end
% Handle the periodic boundaries for x and y:
%left = mod((i-1)-1,Lx) + 1; % i-1, maps 0 to Lx.
%right = mod((i+1)-1,Lx) + 1; % i+1, maps Lx+1 to 1.
if j<k+1 %depth of wall
rho_rhs(j) = 0;
rho(j) = 0;
elseif j<(20+k)
rho_rhs(j) = (1 - rho(j))*exp((beta*((3/2)*rho(j-1) + (3/2)*rho(j+1) + 2*rho(j) + MU - potential(j)));
else
rho_rhs(j) = rho_rhs(j-1);
end
end
end
conv = sum(sum((rho - rho_rhs).^2)); % Convergence value is the sum of the differences between new and current solution.
rho = alpha*rho_rhs + (1 - alpha)*rho; % Mix the new and current solutions for next iteration.
disp(['conv = ' num2str(conv) ' cnt = ' num2str(cnt)]); % Display final answer.
figure(1);
pcolor(rho);
plot(J, rho(1:10));
end
hold off;
The only variable that I'm changing here is mu. I would like to loop my first code so that I can enter an arbitrary amount of different values of mu and plot them on the same graph. Naturally I had to change all of the lists dimension from (1 to size of Ly) to (#of mu(s) to size of Ly), such that when the first code is being looped, the i-th mu value in that loop is being turned into lists with dimension as long as Ly. So I thought I would do the plotting within the loop and use "hold on" encapsulating the whole loop so that every plot that was generated in each loop won't be erased. But I've been spending hours on trying to figure out the semantics of MATLAB but ultimately I can't figure out what to do. So hopefully I can get some help on this!
hold on only applies to the active figure, it is not a generic property shared among all figures. What is does is changing the value of the current figure NextPlot property, which governs the behavior when adding plots to a figure.
hold on is equivalent to set(gcf,'NextPlot','add');
hold off is equivalent to set(gcf,'NextPlot','replace');
In your code you have:
figure(3); % Makes figure 3 the active figure
hold on; % Sets figure 3 'NextPlot' property to 'add'
% Do some things %
while conv>=tol && cnt<count
% Do many things %
figure(1); % Makes figure 1 the active figure; 'hold on' was not applied to that figure
plot(J, rho(1:10)); % plots rho while erasing the previous plot
end
You should try to add another hold on statement after figure(1)
figure(1);
hold on
plot(J, rho(1:10));

Line fitting using RANSAC

I am doing a project in image processing, basically to Vectorise hand drawn images using image processing techniques.
I am using RANSAC in my project. The challenge that I am facing is that the algorithm does not perform the best fit as required but
it uses any two random points and draws a line that joins them as shown in the image below.
RANSAC results
In my algorithm to Vectorise hand drawn images, I also did Grey-scaling, Image thresholding (Image Binarization),
and Skeletonization using Morphological Operators.
I am using MATLAB for my project.
The following is the code I have done so far
% Line fitting using RANSAC
[x, y] =size(skeleton_image);
point =[];
count =1;
% figure; imshow(~data); hold on
for n =1:x
for m =1:y
if skeleton_image(n,m)==1
point(count,1)=m;
point(count,2)=n;
count= count+1;
end
end
end
data = point';
number = size(data,2); % Total number of points
X = 1:number;
iter=100; num=2; thresh = 1000;count_inlines=103; best_count=0; best_line=[];
for i=1:iter
% Randomly select 2 points
ind = randi(number,num); % randperm(number,num);
rnd_points= data(:,ind);
% Fitting line
Gradient = (rnd_points(2,2)-rnd_points(2,1))/(rnd_points(1,2)-rnd_points(1,1));
Constant = rnd_points(2,1)-Gradient*rnd_points(1,1);
Line = Gradient*X+Constant; [j,k]=size(Line);
% How many pixels are in the line?
for i=1:number
Distance = sqrt((Line(:,i)-data(1,i)).^2)+(Line(:,i)-data(2,i)).^2);
if Distance<=thresh
inlines = data(:,i);
count_inlines=countinlines+1;
best_line=Line;
end
I think your issue might be in the way you are counting the distance and/or the threshold that is currently 1000. It might choose all the points in any case and just pick the first or the last ransac line.
% Line fitting using RANSAC
%create skeleton_image objects
skeleton_image = zeros(50,50);
% draw a circle
circle_center = [15,15];
radius = 6;
for i=1:50
for j = 1:50
if abs( radius - sqrt( (i-circle_center(1))^2 + (j-circle_center(2))^2 ) ) <0.5 % < controls the thickness of the circle
skeleton_image(i,j) = 1;
endif
end
end
% draw a line
grad=0.5;
dy = 20;
for i=10:50
skeleton_image(ceil(dy + grad*i),i)=1;
if (i < 50)
skeleton_image(ceil(dy + grad*i)+1,i)=1;
endif
end
% a handful of random points to make it more realistic
skeleton_image(20,22)=1;
skeleton_image(30,7)=1;
skeleton_image(18,45)=1;
skeleton_image(10,10)=1;
skeleton_image(20,23)=1;
skeleton_image(31,6)=1;
skeleton_image(19,45)=1;
skeleton_image(9,13)=1;
skeleton_image(20,24)=1;
skeleton_image(31,5)=1;
skeleton_image(18,46)=1;
% [x, y] =size(skeleton_image);
x = 50;
y = 50;
points =[];
count =1;
for n =1:x
for m =1:y
if skeleton_image(n,m)==1
points(count,1)=m;
points(count,2)=n;
count= count+1;
end
end
end
best_line = [];
best_count = 0;
line_point_list = [];
% how close the pixel has to be to the line to be accepted
threshold = 1;
% how many samples are taken
steps = 10;
for i=1:steps
% pick two points
ind1 = randi(number,1);
ind2 = randi(number,1);
point1 = points(ind1,:);
point2 = points(ind2,:);
%auxiliaries
line = [point1;point2];
lpl = []; %line_point_list
count_i = 0;
if point1 != point2
vector1 = point2-point1;
% unit vector
vector1_normalized = vector1 ./ norm(vector1);
% normal direction of the line
normal_of_vector1 = [vector1_normalized(2), -vector1_normalized(1)];
% loop over points
for j = 1:size(points)
% calculate distance
normal_of_vector1;
vector2 = points(j,:) - point1;
distance = abs(dot(vector2, normal_of_vector1));
if ( distance < threshold )
count_i +=1;
lpl(count_i,:) = points(j,:);
endif
end
endif
if ( count_i > best_count)
best_count = count_i;
best_line = line;
line_point_list = lpl;
endif
end
%best_c
%best_l
%line_point_list
% draw found points
for i=1:size(line_point_list)
skeleton_image(line_point_list(i,2),line_point_list(i,1) ) = 0.25;
end
%visualize
figure(1)
imshow(skeleton_image)

How to run two loops in alternating fashion on Matlab?

I would like to use Matlab to compute two finite difference loops in such a manner that if we have two equations, let's say (1) and (2), it completes one step of (1) then solves (2) for one step then (1) for the next step and then (2) and so on and so forth.
To this end, I provide the parameters of my code below:
%% Parameters
L = 5; % size of domain
T = 5; % measurement time
dx = 1e-2; % spatial step
dt = 1e-3; % time step
x0 = 0;
c = 1;
%%
t = 0:dt:T; % time vector
x = (0:dx:L)'; % spatial vector
nt = length(t);
nx = length(x);
Lx = (1/dx^2)*spdiags(ones(nx,1)*[1 -2 1],-1:1,nx,nx); % discrete Laplace operator
mu = dt/dx;
I = eye(nx,nx); % identity matrix
A = spdiags(ones(nx,1)*[-1 1 0],-1:1,nx,nx); % finite difference matrix
Then the first loop is given by
%% Finite Difference Equation (1)
% preallocate memory
u = zeros(nx,nt);
v = zeros(nx,nt);
% initial condition in time
u(:,1) = sinc((x-x0)/dx);
v(:,1) = sinc((x-x0)/dx);
for i = 1:nx-1
u(:,i+1) = ((1/(c*dt))*I+(1/dx)*A)\((1/(c*dt))*u(:,i)+v(:,i));
end
and the second equation (2) is given by
%% Finite Difference Equation (2)
% preallocate memory
u = zeros(nx,nt);
v = zeros(nx,nt);
% final condition in time
u(:,nt) = sinc((x-x0)/dt);
% initial condition in space
for j = nt:-1:2
v(:,j-1) = ((1/dx)*A+(1/(c*dt))*I)\((1/(c*dt))*v(:,j)
end
In the current format, Matlab will run the first loop i = 1:nx-1 and then the second loop j = nt:-1:2.
But I want to run the two loops as follows: i = 1, then j = nt, then i = 2, then j = nt-1 and so on and so forth. How should I code this?
You can composite two loops like the following:
% define other variables and preallocations
j = nt;
for i = 1:nx-1
u(:,i+1) = ((1/(c*dt))*I+(1/dx)*A)\((1/(c*dt))*u(:,i)+v(:,i));
v(:,j-1) = ((1/dx)*A+(1/(c*dt))*I)\((1/(c*dt))*v(:,j)
j = j - 1;
end
for i = 1:nx-1
u(:,i+1) = ((1/(c*dt))*I+(1/dx)*A)\((1/(c*dt))*u(:,i)+v(:,i));
%This if will be true once each 10 iterations
if(mod((nt-i),10)==0)
j=((nt-i)/10)+1;
v(:,j-1) = ((1/dx)*A+(1/(c*dt))*I)\((1/(c*dt))*v(:,j);
end
end
Don't really know if this will work, but making it more usable as you are trying my idea.

Multiplying a vector times the inverse of a matrix in Matlab

I have a problem multiplying a vector times the inverse of a matrix in Matlab. The code I am using is the following:
% Final Time
T = 0.1;
% Number of grid cells
N=20;
%N=40;
L=20;
% Delta x
dx=1/N
% define cell centers
%x = 0+dx*0.5:dx:1-0.5*dx;
x = linspace(-L/2, L/2, N)';
%define number of time steps
NTime = 100; %NB! Stability conditions-dersom NTime var 50 ville en fått helt feil svar pga lambda>0,5
%NTime = 30;
%NTime = 10;
%NTime = 20;
%NTime = 4*21;
%NTime = 4*19;
% Time step dt
dt = T/NTime
% Define a vector that is useful for handling teh different cells
J = 1:N; % number the cells of the domain
J1 = 2:N-1; % the interior cells
J2 = 1:N-1; % numbering of the cell interfaces
%define vector for initial data
u0 = zeros(1,N);
L = x<0.5;
u0(L) = 0;
u0(~L) = 1;
plot(x,u0,'-r')
grid on
hold on
% define vector for solution
u = zeros(1,N);
u_old = zeros(1,N);
% useful quantity for the discrete scheme
r = dt/dx^2
mu = dt/dx;
% calculate the numerical solution u by going through a loop of NTime number
% of time steps
A=zeros(N,N);
alpha(1)=A(1,1);
d(1)=alpha(1);
b(1)=0;
c(1)=b(1);
gamma(1,2)=A(1,2);
% initial state
u_old = u0;
pause
for j = 2:NTime
A(j,j)=1+2*r;
A(j,j-1)=-(1/dx^2);
A(j,j+1)=-(1/dx^2);
u=u_old./A;
% plotting
plot(x,u,'-')
xlabel('X')
ylabel('P(X)')
hold on
grid on
% update "u_old" before you move forward to the next time level
u_old = u;
pause
end
hold off
The error message I get is:
Matrix dimensions must agree.
Error in Implicit_new (line 72)
u=u_old./A;
My question is therefore how it is possible to perform u=u_old*[A^(-1)] in Matlab?
David
As knedlsepp said, v./A is the elementwise division, which is not what you wanted. You can use either
v/A provided that v is a row vector and its length is equal to the number of columns in A. The result is a row vector.
A\v provided that v is a column vector and its length is equal to the number of rows in A
The results differ only in shape: v/A is the transpose of A'\v'

Simulate 1,000 geometric brownian motions in MATLAB

I currently have code to simulate a geometric Brown motion, courtesy of http://www-math.bgsu.edu/~zirbel/sde/matlab/index.html.
However, I would like to generate 1,000 simulations and to be to display them in a graph.
The codes I have at the moment to generate a single simulation are as follows:
% geometric_brownian(N,r,alpha,T) simulates a geometric Brownian motion
% on [0,T] using N normally distributed steps and parameters r and alpha
function [X] = geometric_brownian(N,r,alpha,T)
t = (0:1:N)'/N; % t is the column vector [0 1/N 2/N ... 1]
W = [0; cumsum(randn(N,1))]/sqrt(N); % S is running sum of N(0,1/N) variables
t = t*T;
W = W*sqrt(T);
Y = (r-(alpha^2)/2)*t + alpha * W;
X = exp(Y);
plot(t,X); % plot the path
hold on
plot(t,exp(r*t),':');
axis([0 T 0 max(1,exp((r-(alpha^2)/2)*T+2*alpha))])
title([int2str(N) '-step geometric Brownian motion and its mean'])
xlabel(['r = ' num2str(r) ' and alpha = ' num2str(alpha)])
hold off
That code cannot be used directly to simulate 1,000 paths/simulations. Unfortunately, it has not been vectorized. The easiest way to do what you want is to use a for loop:
N = 1e3;
r = 1;
alpha = 0.1;
T = 1;
npaths = 1e3; % Number of simulations
rng(0); % Always set a seed
X = zeros(N+1,npaths); % Preallocate memory
for i = 1:n
X(:,i) = geometric_brownian(N,r,alpha,T);
hold on
end
t = T*(0:1:N).'/N;
plot(t,exp(r*t),'r--');
This is rather slow and inefficient. You will need to modify the function a lot to vectorize it. One thing that would improve performance is if you at least removed the plotting code from inside the function and ran that separately after the loop.
Another alternative might be to use the sde_gbm function in my SDETools toolbox, which is fully-vectorized and much faster:
N = 1e3;
r = 1;
alpha = 0.1;
T = 1;
npaths = 1e3; % Number of simulations
t = T*(0:1:N)/N; % Time vector
y0 = ones(npaths,1); % Vector of initial conditions, must match number of paths
opts = sdeset('RandSeed',0,'SDEType','Ito'); % Set seed
y = sde_gbm(r,alpha,t,y0,opts);
figure;
plot(t,y,'b',t,y0*exp(r*t),'r--');
xlabel('t');
ylabel('y(t)');
title(['Geometric Brownian motion and it's mean: ' int2str(npaths) ...
' paths, r = ' num2str(r) ', \alpha = ' num2str(alpha)]);
In either case, one obtains a plot that looks something like this
To perform 1000 simulations, the straightforward way would be:
Nsims = 1000;
N=10^15; % set to length of individual sim
r = 1;
alpha = 0.1;
T = 1;
t = (0:1:N)'/N;
t = (T*(r-(alpha^2)/2))*t;
W = cat(1,zeros(1,Nsims),cumsum(randn(N,Nsims)));
W = W*(sqrt(T)*alpha/sqrt(N));
Y = repmat(t,1,Nsims) + W;
X = exp(Y);
Plotting is just like before
plot(t,X); % plots ALL 1000 paths
% plot(t,X(:,paths)); % use instead to show only selected paths (e.g. paths =[1 2 3])
hold on
plot(t,exp(r*t),':');
axis([0 T 0 max(1,exp((r-(alpha^2)/2)*T+2*alpha))])
title([int2str(N) '-step geometric Brownian motion and its mean'])
xlabel(['r = ' num2str(r) ' and alpha = ' num2str(alpha)])
hold off
For comparatively short (small) sets of simulations looping over your code or executing the above should do. For heavy duty simulations you may benefit from Horchler's promised speed advantage.