Convert from mathematica to matlab

Click For Summary

Discussion Overview

The discussion revolves around converting a Mathematica code snippet into MATLAB, specifically focusing on simulating a one-dimensional random walk and calculating the mean square distance. Participants explore various coding approaches, syntax differences, and mathematical interpretations between the two programming environments.

Discussion Character

  • Technical explanation
  • Mathematical reasoning
  • Debate/contested

Main Points Raised

  • One participant presents a Mathematica function for a random walk and attempts to replicate it in MATLAB, encountering issues with the output of the mean square distance.
  • Another participant questions the use of certain MATLAB syntax and suggests that the participant's function definitions may not be correct, particularly regarding the handling of function arguments.
  • There is a discussion about the proper way to fill an array in MATLAB, with suggestions to avoid using loops and instead utilize vectorized operations.
  • Some participants express confusion over the mathematical definitions and the expected behavior of the code, particularly regarding the calculation of the mean square distance.
  • One participant identifies that the calculation of the mean square distance may be incorrectly implemented, suggesting that the sum of squares should be computed instead of the square of the sum.
  • Another participant proposes a revised approach to ensure that the random walk starts at zero and discusses the implications of this on the results.
  • There are multiple edits and corrections made by participants as they refine their code and address issues with the output values.

Areas of Agreement / Disagreement

Participants express differing views on the correctness of the MATLAB code and the mathematical interpretations of the functions. While some participants agree on certain coding practices, there is no consensus on the final implementation or the expected results of the calculations.

Contextual Notes

Participants note limitations in their understanding of both Mathematica and MATLAB, leading to confusion over syntax and mathematical operations. There are unresolved issues regarding the expected output values and the proper handling of random walks in the context of the problem.

Who May Find This Useful

This discussion may be useful for individuals interested in programming in MATLAB, particularly those transitioning from Mathematica, as well as those studying random walks and mean square distance calculations in a computational context.

ggeo1
Messages
61
Reaction score
0
Hello ,i have the following problem in mathematica and want to do it in matlab.

mathematica :
Code:
...
Walk1D[n_] :=  FoldList[Plus, 0, steps[n]]
LastPoint1D[n_] := Fold[Plus, 0, steps[n]]
...
nsteps = 200; nsq = Floor[Sqrt[nsteps]];
MeanSquareDistance1D[n_Integer, m_Integer] := 
    N[Sum[LastPoint1D[n]^2, {m}]/m]
r2D=MeanSquareDistance1D[100, 1000]

data = Map[({#, MeanSquareDistance1D[#,2000]})&,
          Range[10, 90, 20]]

And i did this :
Code:
Walk1D =@ (n) cumsum(steps(n));
LastPoint1D_old=@ (n) cumsum(steps(n));
LastPoint1D=@ (n) LastPoint1D(end);
nsteps=200;
nsq=floor(sqrt(nsteps));
MeanSquareDistance1D= @ (n,m) m*sum(LastPoint1D(n).^2)/.m;
r2D=MeanSquareDistance1D(100,1000)

I have two problems:
1) The result from r2D is always "1" but it must change values.
2) I can't handle the "data" with Map function in mathematica.I now i must do an arrayfun(f,x) and x=10:20:90 but i am confused how to type it.
 
Physics news on Phys.org
For
Code:
data = Map[({#, MeanSquareDistance1D[#,2000]})&,
          Range[10, 90, 20]]

i am doing this :
Code:
for i=10:20:90
    data=arrayfun(MeanSquareDistance1D(i,2000),i)
end

but it gives me: Error using ==> arrayfun
First input must be a function handle.

Of course,it is a function handle as i declared it above.(The r2D value keep remaining the same!)
 
Anyone , a little help??
 
I think you're not getting responses because very few people are experts in both Mathematica and Matlab. I know almost nothing about Mathematica. For example, I don't really know what Sum[LastPoint1D[n]^2, {m}] means. What's {m} for? It would be easier if you just explained mathematically what you are trying to do.

On the Matlab side, your definition “LastPoint1D=@ (n) LastPoint1D(end)” makes no sense at all. You are defining a function that is itself? On top of that, the argument n is ignored completely. some_matrix(end) simply returns the last element in the matrix, so LastPoint1D(1) would be the same as LastPoint1D(23546).

Also, in "m*sum(LastPoint1D(n).^2)/.m", “/.” is not an appropriate operator (unless this is some new feature in Matlab I don't know about). Do you mean “./”?

You probably don't need arrayfun. You just need to write your script the Matlab way. Matlab let's you index matrices with vectors and calculate everything at once. No need for any loops.
 
Hello,this is my new code :

Code:
steps=@ (m) randi(3,1,m)-2;

Walk1D =@ (n) cumsum(steps(n));
findend=@ (x) x(end);
LastPoint1D=@(n) findend(Walk1D(n));


nsteps=200;
nsq=floor(sqrt(nsteps));
MeanSquareDistance1D= @ (n,m) m*sum((LastPoint1D(n)).^2)./m;
r2D=MeanSquareDistance1D(100,1000)


data=zeros(5,2);
for i=10:20:90
 data(i,:)=[i,MeanSquareDistance1D(i,2000)]
end

The problems are:
1) The r2D gives me very small numbers(10^-2 - 10^-3) but in original code(mathematica)gives 10-100.
2)I want a different way to fill "data" because i want data to be a 5x2 matrix and display it.
3) If i plot(data) ,it gives me the right graph but also with a line of points onto the x-axis.If i try plot(data(:,1),data(:,2)) it gives me wrong graph.


The LastPoint[n] defines the last position.
The mean square distance defined as the mean value in a collection from m different orbits of n steps,for each one of them computes the square of the distance between its beginning and end and then is computed the mean value.


EDIT-->> For the small values ,the problem was that i didn't multiply with m>The correct is "MeanSquareDistance1D= @ (n,m) m*sum((LastPoint1D(n)).^2)./m;"
The other problems still exist.
 
Last edited:
One odd thing: LastPoint1D(n) always returns a number, so m*sum((LastPoint1D(n)).^2)./m is equal to LastPoint1D(n)^2 and m has no effect at all.
3) If i plot(data) ,it gives me the right graph but also with a line of points onto the x-axis.If i try plot(data(:,1),data(:,2)) it gives me wrong graph.
In your for loop, when you write: data(i,:)=[i,MeanSquareDistance1D(i,2000)], i is 10, 30, 50..., so you are telling Matlab: data(10, :)=..., data(30, :)=..., and Matlab expands the matrix. In the end, you have a 90x2 matrix with only a few rows filled with values, the rest are zeros.

Do it like this:
Code:
data=[];
for i=10:20:90
  data=[data; i MeanSquareDistance1D(i,2000)];
end

Then plot(data(:, 1), data(:, 2)).
 
Hello, m has an effect because if i don' put it for example,i take very small numbers.I think that part its ok.
With the code you gave me ,the filling of the "data" it's ok but we have a problem!
It supposes to give me sth like:
10, 10.184
30, 27.51
50, 50.306
70, 68.394
90, 90.414

The 2nd column must give approximately the numbers of the 1st column in order to plot a straight line.But with my code it gives me for example:

data =

10 0
30 9
50 49
70 9
90 100

Somewhere ,sth is wrong but i can't figure...
Thanks for helping.

EDIT--->>
I am correcting to:
steps=@ (m) 2*randi([0,1],[1,m])-1; -->it must give me (-1,1)
but still the problem with "data" 2nd column.
 
Last edited:
I think i tracked the problem but i can't express it.It has to do with what you said.
I want the Walk1D and the LastPoint1D to begin always with zero!
For example,as many times as i execute the code,the Walk1D[10] must give me:
{0, -1, 0, 1, 2, 1, 2, 3, 4, 3, 4}
{0, 1, 2, 1, 2, 1, 0, 1, 0, -1, -2} and so on.

But ,in my code this doesn;t happen.

I have: Walk1D =@ (n) cumsum(steps(n));
I don't know how to do it.If i try "Walk1D =@ (n) cumsum(0:steps(n));"
it doesn't work..

EDIT-->> I did this :Walk1D =@ (n) [0,cumsum(steps(n))]; but i don't know if its right(it didn't fixed the problem though)
 
Last edited:
I think your main problem is that you are calculating the square of the sum, instead of calculating the sum of the squares.
 
  • #10
I think i am doing it right.??

m*sum((LastPoint1D(n)).^2)
 
  • #11
LastPoint1D(n) is already the sum of the steps. It's a number, so summing it does nothing. The last element of cumsum is the total sum. What you are really calculating is sum(steps(n))^2. You need to calculate sum(steps(n).^2).
 
  • #12
Ok, i unsterstood what you say.But ,i thought every time i call LastPoint(n) it calls Walk1D which is calls steps.That way LastPoint(n) won't be only a number.

I tried the " sum(steps(n).^2" but now it gives me exactly :
10
30
50
70
90

It should give me approximately the above numbers ,as i said before.
We are so close!
Any idea?
And thanks!
 
  • #13
The mean square distance defined as the mean value in a collection from m different orbits of n steps,for each one of them computes the square of the distance between its beginning and end and then is computed the mean value.
After re-reading this, I sort of understand what you are trying to do. The problem with the code is that you are not really doing the “compute the mean value in a collection of m orbits” part. Your code is essentially setting m=1. That's why m did not have any effect.

Based on your definition, the correct Matlab code is:

Code:
steps=@ (n, m) randi([-1 1], n, m);
LastPoint1D=@ (n, m) sum(steps(n, m));
MeanSquareDistance1D= @  (n,m) mean(LastPoint1D(n, m).^2);

steps returns a 2D matrix (rows=n steps, columns=m orbits). When it is summed to get the difference between start and end position, it becomes a vector (columns=m orbits) which can then be squared and averaged.

The value returned by MeanSquareDistance1D(n, m) is around n/2, but that's easy to understand if you think about the random distribution.

If you want to calculate Walk1D first, index the result of cumsum using (end, :) to get LastPoint1D as the last point of each column.
 
Last edited:
  • #14
Hello!Finally it worked!Thank you very much for your effort.
I left the code as it was but i added :

steps1=@ (n, m) randi([-1 1], n, m);
LastPoint_1D=@ (n, m) sum(steps1(n, m));
MeanSquareDistance1D = @(n,m) mean(LastPoint_1D(n,m).^2);

The only <<problem>> (as you said (n/2)) is that the values i am taking are too small,for example:
data =

10.0000 6.9790
30.0000 20.7105
50.0000 33.2900
70.0000 44.5420
90.0000 57.0020

The graph still is straight but with smaller slope.
 
  • #15
I am trying to do now :
Code:
nsteps=10:20:90;
pol=polyfit(nsteps,data,1)

or

Code:
nsteps=10:20:90;
pol=polyfit(nsteps,data(:,2),1)

but it gives me

Error using ==> polyfit at 48
X and Y vectors must be the same size.

Error in ==> randomwalk1d at 55
pol=polyfit(nsteps,data,1)

but nsteps and data(:,2) are the same size!

If you could tell what to do..

EDIT -->> I found it
I wrote :
pol=polyfit(nsteps,data(:,2)',1)
 
Last edited: