MATLAB: Error using scatter (line 61) X and Y must be vectors of the same length. Error in (line 20) scatter(x,y) … WHY

brownianmotionerror

clear ;
clc;
n=300;
t=100;
x = zeros(n,t);
y = zeros(n,t);
xtrack = zeros(n,t);
ytrack = zeros(n,t);
for i= 2:t
for j=1:n
dx = rand(n,t);
dy = rand(n,t);
x= x + dx;
y= y + dy;
end
x =[dx;x]; xtrack;
y =[dy;y]; ytrack;
scatter(x,y)
axis({ x x y y})
pause (0.01)
end
Could anyone help push me in the right direction , i have been trying to compute amodel that mimics the random steps of molecules undergoing Brownian motion. this has to track 300 molecules in an array and repeat this for 100 time steps
I have attempted different ways but I keep getting an error messaged that disagrees with my code , i have tripled checked the vector lengths and they do agree unless i am missing something. Thanks a lot for reading
this is the message i keep getting regardless what i alter –> Error using scatter (line 61) X and Y must be vectors of the same length. Error in (line 20) scatter(x,y)
please see below my code

Best Answer

The important part is that they need to be vectors . Yours are arrays .
scatter(x(:), y(:))
However,
for i= 2:t
for j=1:n
dx = rand(n,t);
dy = rand(n,t);
x= x + dx;
y= y + dy;
end
so each j iteration, you generate a bunch of forward random motions (no negative offsets when there should be), and add them to the current locations, giving updated locations.
x =[dx;x]; xtrack;
then you take the last set of random values and put it at the top of the set of random variables ?? So x would become (2*n, t) in size after the first round. And then you tell MATLAB to pull xtrack out of memory, and get it ready for displaying, but then not to display it because of the semi-colon; you do not store into xtrack.
Then you do something similar for y, and proceed to the plot, which fails. The scatter() I post above will get past that.
Now you loop back, and x is 2*n by t in size, and you generate new random values of size n by t. Then you try to add the (2*n by t) array and the (n by t) array... which is going to fail.
I would suggest to you that if you have 300 molecules to track, that it is not necessary to generate 300 different random matrices of size 300 x 100 per time step
Related Question