MATLAB, what is the best way to trace a boarder in a matrix that is changing each step?

回眸只為那壹抹淺笑 提交于 2019-12-11 04:49:08

问题


I want to calculate the average slope or gradient at each iteration in such a matrix.

a=[ 10 9 8 7 6 5 5;
9  9 8 7 8 5 5; 
8  8 7 7 5 5 5; 
7  7 7 6 5 5 5;
6  6 6.6 5 5 5 5;
6  6 6.1 5 5 5 5;
6.3  5 5 5 5 5 5]

Where I am wanting to find the slope or gradient between the a(1,1) position during each step and at each point that boarders a value of 5. Each iteration the position of the 5's changes and so do the other values.

After doing so I will then average the slope. I haven't encountered a problem like this yet and I could not find a Matlab command to simplify.


回答1:


First you must find out which the coast elements are. From your definition, an element is a coast element if it border (from the right) with a 5. If the sea level is 5, and is the lowest possible value i.e. no element goes beyond sea level, then you must first find all the land elements as,

land=a>5;

This returns,

ans =

     1     1     1     1     1     0     0
     1     1     1     1     1     0     0
     1     1     1     1     0     0     0
     1     1     1     1     0     0     0
     1     1     1     0     0     0     0
     1     1     1     0     0     0     0
     1     0     0     0     0     0     0

Now, the coast elements are 1s that are followed by a 0. Take the column difference of the land matrix,

coastTmp=diff(land,1,2);

returning,

ans =

     0     0     0     0    -1     0
     0     0     0     0    -1     0
     0     0     0    -1     0     0
     0     0     0    -1     0     0
     0     0    -1     0     0     0
     0     0    -1     0     0     0
    -1     0     0     0     0     0

and find the -1s,

coast=find(coastTmp==-1);

which are,

coast =

     7
    19
    20
    24
    25
    29
    30

From here it is easy. The gradient is the difference of a(1,1) with all the coast elements, i.e.

slope=a(coast)-a(1,1);  % negative slope here

giving,

slope =

  -3.700000000000000
  -3.400000000000000
  -3.900000000000000
  -3.000000000000000
  -4.000000000000000
  -4.000000000000000
  -2.000000000000000

and of course the mean is,

mean(slope);


来源:https://stackoverflow.com/questions/8773466/matlab-what-is-the-best-way-to-trace-a-boarder-in-a-matrix-that-is-changing-eac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!