I want to plot the graph of the numerical solution of bisection method and show how it get close to the real solution .
my code:
% f=input('please enter the function:');
% xL=input('please enter the limits .from:');
% XR=input('to:');
% eps=input('please enter epsilon:');
f=#(x)x.^2-1;
XR=2;
xL=-2;
XL=xL ;
eps=0.001;
subplot(2,1,1);
title('graph 1');
ezplot(f);
hold on ;
% line([0 0],40);
% line(-40,[0 0]);
plot(XR,f(XR),'r*');
plot(xL,f(xL),'r*');
disp( 'the answers is : ');
for df=xL:0.15:XR
if f(xL)*f(df)<= 0
xR=df;
Roots = BisectionM(f,xR,xL,eps);
plot(Roots,f(Roots),'gs');
disp(Roots);
xL=df;
xR=XR;
end
end
subplot(2,1,2);
title('graph 2');
x0=fzero(f,xL);
sol = BisectionM(f,xR,xL,eps);
plot(1:1:100,ones(1,100)*x0);
hold on ;
plot(1:1:100,sol);
the function :
function[sol,Roots] = BisectionM(f,xR,xL,eps)
while abs(xR - xL) > eps
xM = (xR + xL) / 2;
if (f(xL))*(f(xM)) > 0
xL = xM;
sol=xM;
plot(xL,f(xL),'.');
else
xR = xM;
plot(xR,f(xR),'.');
sol=xM;
end
Roots = xM;
end
end
I don't know how to plot this so it will get closer to the solution (the blue line at the end). anyone?
I do not understand many things in your code, e.g. why BisectionM has two identical outputs under different variable names (sol, Roots), moreover only one output is used throughout the main function. Besides here is my guess what you might want:
The figure shows how the numerical solution converges with respect to iteration number. For this you have to store the iteration results in a vector (sol), please see below the modified code:
main.m
f=#(x)x.^2-1;
XR=2;
xL=-2;
XL=xL ;
eps=0.001;
subplot(2,1,1);
title('graph 1');
ezplot(f);
hold on ;
% line([0 0],40);
% line(-40,[0 0]);
plot(XR,f(XR),'r*');
plot(xL,f(xL),'r*');
disp( 'the answers is : ');
for df=xL:0.15:XR
if f(xL)*f(df)<= 0
xR=df;
Roots = BisectionM(f,xR,xL,eps);
plot(Roots(end),f(Roots(end)),'gs');
disp(Roots(end));
xL=df;
xR=XR;
end
end
subplot(2,1,2);
title('graph 2');
% give the wide interval again because it was changed previously
XR=2;
xL=-2;
x0=fzero(f,xL);
Roots = BisectionM(f,xR,xL,eps);
plot(1:length(Roots),ones(length(Roots),1)*x0, 'g');
hold on ;
plot(1:length(Roots),Roots,'Marker', '.');
xlabel('iteration number')
BisectionM.m
function Roots = BisectionM(f,xR,xL,eps)
% no preallocation because of while
ii = 1;
while abs(xR - xL) > eps
xM = (xR + xL) / 2;
if (f(xL))*(f(xM)) > 0
xL = xM;
sol=xM;
plot(xL,f(xL),'.');
else
xR = xM;
plot(xR,f(xR),'.');
sol=xM;
end
Roots(ii) = xM;
ii = ii + 1;
end
end
Related
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));
Suppose I have a 5x5 matrix.
The elements of the matrix change (are refreshed) every second.
I would like to be able to display the matrix (not as a colormap but with the actual values in a grid) in realtime and watch the values in it change as time progresses.
How would I go about doing so in MATLAB?
A combination of clc and disp is the easiest approach (as answered by Tim), here's a "prettier" approach you might fancy, depending on your needs. This is not going to be as quick, but you might find some benefits, such as not having to clear the command window or being able to colour-code and save the figs.
Using dispMatrixInFig (code at the bottom of this answer) you can view the matrix in a figure window (or unique figure windows) at each stage.
Example test code:
fig = figure;
% Loop 10 times, pausing for 1sec each loop, display matrix
for i=1:10
A = rand(5, 5);
dispMatrixInFig(A,fig)
pause(1)
end
Output for one iteration:
Commented function code:
function dispMatrixInFig(A, fig, strstyle, figname)
%% Given a figure "fig" and a matrix "A", the matrix is displayed in the
% figure. If no figure is supplied then a new one is created.
%
% strstyle is optional to specify the string display of each value, for
% details see SPRINTF. Default is 4d.p. Can set to default by passing '' or
% no argument.
%
% figname will appear in the title bar of the figure.
if nargin < 2
fig = figure;
else
clf(fig);
end
if nargin < 3 || strcmp(strstyle, '')
strstyle = '%3.4f';
end
if nargin < 4
figname = '';
end
% Get size of matrix
[m,n] = size(A);
% Turn axes off, set origin to top left
axis off;
axis ij;
set(fig,'DefaultTextFontName','courier', ...
'DefaultTextHorizontalAlignment','left', ...
'DefaultTextVerticalAlignment','bottom', ...
'DefaultTextClipping','on');
fig.Name = figname;
axis([1, m-1, 1, n]);
drawnow
tmp = text(.5,.5,'t');
% height and width of character
ext = get(tmp, 'Extent');
dy = ext(4);
wch = ext(3);
dwc = 2*wch;
dx = 8*wch + dwc;
% set matrix values to fig positions
x = 1;
for i = 1:n
y = 0.5 + dy/2;
for j = 1:m
y = y + 1;
text(x,y,sprintf(strstyle,A(j,i)));
end
x = x + dx;
end
% Tidy up display
axis([1-dwc/2 1+n*dx-dwc/2 1 m+1]);
set(gca, 'YTick', [], 'XTickLabel',[],'Visible','on');
set(gca,'XTick',(1-dwc/2):dx:x);
set(gca,'XGrid','on','GridLineStyle','-');
end
I would have thought you could achieve this with disp:
for i=1:10
A = rand(5, 5);
disp(A);
end
If you mean that you don't want repeated outputs on top of each other in the console, you could include a clc to clear the console before each disp call:
for i=1:10
A = rand(5, 5);
clc;
disp(A);
end
If you want to display your matrix on a figure it is quite easy. Just make a dump matrix and display it. Then use text function to display your matrix on the figure. For example
randMatrix=rand(5);
figure,imagesc(ones(20));axis image;
hold on;text(2,10,num2str(randMatrix))
If you want to do it in a for loop and see the numbers change, try this:
for i=1:100;
randMatrix=rand(5);
figure(1),clf
imagesc(ones(20));axis image;
hold on;text(2,10,num2str(randMatrix));
drawnow;
end
while implementing kernel based grapg cut method, I am getting error at line: area(1+1)=999999999;
suggestion for correcting the error is line 147: the variable 'area' appears to change size on every loop iteration(within a script).
Considering preallocation for speed, please suggest me how to preallocate the variable area,in the matlab code?
Code:
clear all; close all;
%%%%%%%%%%%%%%%%%%%%%%%Main inputs and parameters%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%Note: The RBF-kernel parameters are given in function kernel RBF.m%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%Example with a color image%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%path = 'Images\Color_image.jpg';
%im = im2double(imread(path));
%alpha=1; %The weight of the smoothness constraint
%k =8; %The number of regions
%%%%%%%Example with a SAR image corrupted with a multiplicative noise%%%%%%
%%%%%%%%%%%%%%%%Uncomment the following to run the example)%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
path = 'Images\Sar_image.tif';
im = im2double(imread(path));
alpha=0.6;
k =4;
%%%%%%%%%%%%%%%%%%%%%%%%%%Example with a brain image%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%Uncomment the following to run the example)%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%path = 'Images\Brain_image.tif';
%im = im2double(imread(path));
%alpha=0.1;
%k =4;
sz = size(im);
Hc=ones(sz(1:2));
Vc=Hc;
i_ground = 0; % rank of the bakground for plotting, 0: the darkest;
%k-1 the brightest; 99: nowhere
diff=10000;
an_energy=999999999;
iter=0;
iter_v=0;
energy_global_min=99999999;
distance = 'sqEuclidean'; % Feature space distance
% Initialization: cluster the data into k regions
tic,
disp('Start kmeans');
data = ToVector(im);
[idx c] = kmeans(data, k, 'distance', distance,'EmptyAction','drop','maxiter',100);
c=c(isfinite(c(:,1)),:);
k=size(c,1);
k_max=k;
kmean_time=toc;
Dc = zeros([sz(1:2) k],'single');
c;
tic
while iter < 5
iter=iter+1;
clear Dc
clear K
c;
for ci=1:k
K=kernel_RBF(im,c(ci,:));
Dc(:,:,ci)=1-K;
end
clear Sc
clear K
%% The smoothness term
Sc = alpha*(ones(k) - eye(k));
gch = GraphCut('open', Dc, Sc, Vc, Hc);
[gch L] = GraphCut('swap',gch);
[gch se de] = GraphCut('energy', gch);
nv_energy=se+de;
gch = GraphCut('close', gch);
if (nv_energy<=energy_global_min)
diff=abs(energy_global_min-nv_energy)/energy_global_min;
energy_global_min=nv_energy;
L_global_min=L;
k_max=k;
nv_energy;
iter_v=0;
% Calculate region Pl of label l
if size(im, 3)==3 % Color image
for l=0:k-1
Pl=find(L==l);
card=length(Pl);
K1=kernel_RBF(im(Pl),c(l+1,1));K2=kernel_RBF(im(Pl),c(l+1,2));K3=kernel_RBF(im(Pl),c(l+1,3));
smKI(1)=sum(im(Pl).*K1); smKI(2)=sum(im(Pl+prod(sz(1:2))).*K2); smKI(3)=sum(im(Pl+2*prod(sz(1:2))).*K3);
smK1=sum(K1);smK2=sum(K2);smK3=sum(K3);
if (card~=0)
c(l+1,1)=smKI(1)/smK1;c(l+1,2)=smKI(2)/smK2;c(l+1,3)=smKI(3)/smK3;
else
c(l+1,1)=999999999;c(l+1,2)=999999999;c(l+1,3)=999999999;
end
end
end
if size(im, 1)==1 % Gray-level image
for l=0:k-1
Pl=find(L==l);
card=length(Pl);
K=kernel_RBF(im(Pl),c(l+1,1));
smKI=sum(im(Pl).*K);
smK=sum(K);
if (card~=0)
c(l+1,1)=smKI/smK;
else
c(l+1,1)=999999999;
end
end
end
c=c(c(:,1)~=999999999,:);
c_global_min=c;
k_global=length(c(:,1));
k=k_global;
else
iter_v=iter_v+1;
%---------------------------------
% Begin updating labels
%---------------------------------
% Calculate region Pl of label l
if size(im, 3)==3 % Color image
for l=0:k-1
Pl=find(L==l);
card=length(Pl);
K1=kernel_RBF(im(Pl),c(l+1,1));K2=kernel_RBF(im(Pl),c(l+1,2));K3=kernel_RBF(im(Pl),c(l+1,3));
smKI(1)=sum(im(Pl).*K1); smKI(2)=sum(im(Pl+prod(sz(1:2))).*K2); smKI(3)=sum(im(Pl+2*prod(sz(1:2))).*K3);
smK1=sum(K1);smK2=sum(K2);smK3=sum(K3);
% Calculate contour Cl of region Pl
if (card~=0)
c(l+1,1)=smKI(1)/smK1;c(l+1,2)=smKI(2)/smK2;c(l+1,3)=smKI(3)/smK3;
else
c(l+1,1)=999999999;c(l+1,2)=999999999;c(l+1,3)=999999999;
area(l+1)=999999999;
end
end
end
if size(im, 3)== 1 % Gray-level image
for l=0:k-1
Pl=find(L==l);
card=length(Pl);
K=kernel_RBF(im(Pl),c(l+1,1));
smKI=sum(im(Pl).*K);
smK=sum(K);
% Calculate contour Cl of region Pl
if (card~=0)
c(l+1,1)=smKI/smK;
else
c(l+1,1)=999999999;
area(l+1)=999999999;
end
end
end
c=c(c(:,1)~=999999999,:);
k=length(c(:,1));
end
end
L=L_global_min;
energy_global_min;
c=c_global_min;
size(c,1)
iter;
%Show the results
if size(im, 3)==3 % Color image
img=zeros(sz(1),sz(2),3);
j=1;
imagesc(im); axis off; hold on;
for i=0:k_max-1
LL=(L_global_min==i);
is_zero=sum(sum(LL));
if is_zero
img(:,:,1)=img(:,:,1)+LL*c(j,1);
img(:,:,2)=img(:,:,2)+LL*c(j,2);
img(:,:,3)=img(:,:,3)+LL*c(j,3);
j=j+1;
end
if i~=i_ground
color=[rand rand rand];
contour(LL,[1 1],'LineWidth',2.5,'Color',color); hold on;
end
end
figure(2);
imagesc(img); axis off;
end
if size(im, 3)==1 % Gray-level image
img=zeros(sz(1),sz(2));
j=1;
imagesc(im); axis off; hold on; colormap gray;
for i=0:k_max-1
LL=(L_global_min==i);
is_zero=sum(sum(LL));
if is_zero
img(:,:,1)=img(:,:,1)+LL*c(j,1);
j=j+1;
end
if i~=i_ground
color=[rand rand rand];
contour(LL,[1 1],'LineWidth',2.5,'Color',color); hold on;
end
end
figure(2);
imagesc(img); axis off;
end
A possible solution is to set the variable initially to zeros(k_max, 1 ).
I want to segment an Arabic word into single characters. Based on the histogram/profile, I assume that I can do the segmentation process by cut/segment the characters based on it's baseline (it have similar pixel values).
But, unfortunately, I still stuck to build the appropriate code, to make it works.
% Original Code by Soumyadeep Sinha
% Saving each single segmented character as one file
function [segm] = trysegment (a)
myFolder = 'D:\1. Thesis FINISH!!!\Data set\trial';
level = graythresh (a);
bw = im2bw (a, level);
b = imcomplement (bw);
i= padarray(b,[0 10]);
verticalProjection = sum(i, 1);
set(gcf, 'Name', 'Trying Segmentation for Cursive', 'NumberTitle', 'Off')
subplot(2, 2, 1);imshow(i);
subplot(2,2,3);
plot(verticalProjection, 'b-'); %histogram show by this code
% hist(reshape(input,[],3),1:max(input(:)));
grid on;
% % t = verticalProjection;
% % t(t==0) = inf;
% % mayukh = min(t)
% 0 where there is background, 1 where there are letters
letterLocations = verticalProjection > 0;
% Find Rising and falling edges
d = diff(letterLocations);
startingColumns = find(d>0);
endingColumns = find(d<0);
% Extract each region
y=1;
for k = 1 : length(startingColumns)
% Get sub image of just one character...
subImage = i(:, startingColumns(k):endingColumns(k));
% se = strel('rectangle',[2 4]);
% dil = imdilate(subImage, se);
th = bwmorph(subImage,'thin',Inf);
n = imresize (th, [64 NaN], 'bilinear');
figure, imshow (n);
[L,num] = bwlabeln(n);
for z= 1 : num
bw= ismember(L, z);
% Construct filename for this particular image.
baseFileName = sprintf('char %d.png', y);
y=y+1;
% Prepend the folder to make the full file name.
fullFileName = fullfile(myFolder, baseFileName);
% Do the write to disk.
imwrite(bw, fullFileName);
% subplot(2,2,4);
% pause(2);
% imshow(bw);
end
% y=y+1;
end;
segm = (n);
Word image is as follow:
Why the code isn't work?
do you have any recommendation of another codes?
or suggested algorithm to make it works, to do a good segmentation on cursive character?
Thanks before.
Replace this code part from the posted code
% 0 where there is background, 1 where there are letters
letterLocations = verticalProjection > 0;
% Find Rising and falling edges
d = diff(letterLocations);
startingColumns = find(d>0);
endingColumns = find(d<0);
with the new code part
threshold=max(verticalProjection)/3;
thresholdedProjection=verticalProjection > threshold;
count=0;
startingColumnsIndex=0;
for i=1:length(thresholdedProjection)
if thresholdedProjection(i)
if(count>0)
startingColumnsIndex=startingColumnsIndex+1;
startingColumns(startingColumnsIndex)= i-floor(count/2);
count=0;
end
else
count=count+1;
end
end
endingColumns=[startingColumns(2:end)-1 i-floor(count/2)];
No changes needed for the rest of the code.
clear all; close all; clc;
figure(1)
set(gcf,'Units','normalized','Position',[0 0 1 1])
N = 100;
M = 100;
x(1,M) = 0;
y(1,M) = 0;
for n = 2:1:N
bx = randi([0,1],1,M)*2-1; % binary random number
by = randi([0,1],1,M)*2-1; % binary random number
x(n,:) = x(n-1,:) + bx;
y(n,:) = y(n-1,:) + by;
subplot(1,2,1)
plot(x(:,1),y(:,1),'k')
xlabel('x')
ylabel('y')
axis equal
set(gca,'FontSize',20)
subplot(3,2,6)
plot([0:1:n],sqrt(2*[0:1:n]),'r')
hold on
plot(sqrt(mean(x.^2+y.^2,2)),'k')
xlim([0 N])
xlabel('t')
ylabel('MSD(t)')
set(gca,'FontSize',12)
drawnow()
end
msd = mean(sqrt(2*[0;1;n]));
disp(msd);
msds = mean(sqrt(mean((x.^2+y.^2),2)));
disp(msds);
------ i have tried running and modified the codes above, and fortunately, it was very successful ... its just that the values that will be displayed on "msd" and "msds" have a very large difference .. the values of both must be closer or almost equal .. well, the command i used for calculating both has been successful for the same simulation but its in one-dimensional .. and the above code is two dimensional .. what must i do ??
You have a typo at line 39. Try:
msd = mean(sqrt(2*[0:1:n]));
instead of:
msd = mean(sqrt(2*[0;1;n]));
Then I have the same value for msd and msds.