1

I'm trying to create a random "path" on a coordinate system on Matlab. I am doing this by creating a for loop where for each iteration it fills in a new value on a matrix that has initial values of zeros.

For example, I have 5 points so I have an initial matrix a=[0 0 0 0 0; 0 0 0 0 0] (row1 = x values, row2 = y values).

The path can move right/left or up/down (no diagonals). In my for loop, I call randi(4) and say something like "if randi(4)=1, then move 1 point to the left (x-1). if randi(4)=2, then move to the right (x+1), etc."

The problem is that you cannot visit a specific point more than once. For example, the path can start at (0,0), then go to (0,1), then (1,1), then (1,0), and then it CANNOT go back to (0,0).. in my current code I don't have this restriction so I was hoping I could get some suggestions..

Since in this example the matrix would look something like a=[0 0 1 1 0; 0 1 1 0 0].

I was thinking of maybe subtracting each new coordinate (here (0,0)) from each column on the matrix a and if any of the columns give me values of zero for both rows (since it's the same coordinate subtracted from itself), then go back one step and let randi(4) run again.. but

  1. How could I tell it to "go back one step" (or two or three)?
  2. How do you compare one column against each column of the already established matrix?
  3. This was just an idea.. are there any functions in Matlab that would let me do this? or maybe compare if two columns are the same within a matrix?
4

2 回答 2

1

对你的问题。

  1. 回去 - 我想这意味着只是扔掉矩阵中最右边的列。

  2. 查找它是否存在,您可以使用ismember

不幸的是,它只需要行,所以你需要转置。片段:

a = [1:10; repmat(1:2,1,5)]'
test = ismember(a,[3,2],'rows')
any(test) % not found
test = ismember(a,[3,1],'rows')
any(test) % found

当然你的想法也行。

于 2013-02-14T09:22:39.403 回答
0

我可以回答这个:

您如何将一列与已建立矩阵的每一列进行比较?

使用两个不同的矩阵。使用 setdiff() 函数比较它们:http: //www.mathworks.com/help/matlab/ref/setdiff.html

于 2013-02-14T04:21:52.877 回答