开发者

Comparing adjacent elements in MATLAB

开发者 https://www.devze.com 2022-12-20 05:54 出处:网络
Does anyone know how I can compare the elements in an array with the adjacent elements? For example, if I have an array:

Does anyone know how I can compare the elements in an array with the adjacent elements?

For example, if I have an array:

0 0 0 1 1 1 1 0 
0 1 1 1 1 1 1 0 
0 1 0 1 1 1 1 0
0 1 1 1 1 1 0 0
0 0 0 0 1 1 1开发者_运维问答 1
1 1 1 1 1 1 1 1

Is there a way to cycle through each element and perform a logical test of whether the elements around it are equal to 1?


Oops, it looks like someone is doing a homework assignment. Game of life maybe?

There are many ways to do such a test. But learn to do it in a vectorized form. This involves understanding how matlab does indexing, and how the elements of a 2-d array are stored in memory. That will take some time to explain in detail, more than I want to do at this exact moment. I would definitely recommend you learn it though.

Until then, I'll just suggest that if you really are doing the game of life, then the best trick is to use conv2. Thus,

A =[0     0     0     1     1     1     1     0
    0     1     1     1     1     1     1     0
    0     1     0     1     1     1     1     0
    0     1     1     1     1     1     0     0
    0     0     0     0     1     1     1     1
    1     1     1     1     1     1     1     1];

B = conv2(A,[1 1 1;1 0 1;1 1 1],'same')
B =
    1     2     4     4     5     5     3     2
    2     2     5     6     8     8     5     3
    3     4     8     7     8     7     4     2
    2     2     4     5     7     7     6     3
    3     5     6     7     7     7     6     3
    1     2     2     3     4     5     5     3


Loren has recently posted about this very issue: http://blogs.mathworks.com/loren/2010/01/19/mathematical-recreations-tweetable-game-of-life/ - lots of interesting things can be learned by studying the code in that post and its comments

0

精彩评论

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