开发者

extract a pair from list in matlab

i wanted to ask this: I have in mathematica :

step := {{开发者_JAVA百科0, 1}, {1, 0}, {0, -1}, {-1, 0}} [[RandomInteger[ {1, 4}] ]]

step  --> this takes one list from above (for example {0,1})

steps2D[n_] := Table[step, {n}]

and i did:

a=[0,1];b=[1,0];c=[0,-1];d=[-1,0];
list=[a;b;c;d]
step=@ (rand) rand(1,list) -->> i must extract from here randomly one pair..
step

steps2D=@ (n) arrayfun(step,n);

I have 2 problems: 1) I can't extract from my list randomly one pair. 2) I don't know if i have the step2D right.

EDIT-->> The code continues :

Walk2D[n_] := FoldList[Plus, {0, 0}, steps2D[n]]
Walk2D[10]
LastPoint2D[n_] := Fold[Plus, {0, 0}, steps2D[n]]
LastPoint2D[100]    

I did this :

Walk2D=@ (list,n) cumsum(steps2D(list,n));
Walk2D(list,10)

LastPoint2D = @ (Walk2D) (Walk2D(end));
walk1=Walk2D(list,100);
LastPoint2D(walk1)  -->> This gives me only one number and not a pair as it should


I suppose you want to do the first code example in Matlab. For getting a random element from the array list you could do something like:

rand_row_index = ceil( length(list) * rand(1) );
step = list( rand_row_index, : );

Concerning your second question, I'm not quite sure what you actually want to do, as I'm not familiar with Mathematica. If you want to constitute a matrix consisting of elements, randomly taken from list, you could write a function like

% Create a matrix with n rows that contains random values taken from list.
function result = steps2D(list, n)

    result = zeros(n, size(list, 2));

    for i = 1:n
        rand_row_index = ceil( length(list) * rand(1) );
        step = list( rand_row_index, : );
        result(i, :) = step;
    end

end

And use it like that:

steps = steps2D( list, 30 );

Note, that in Matlab, the function steps2D() must be defined in seperate file, convienently named steps2D.m.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜