MATLAB, what is the best way to trace a boarder in

2019-08-05 09:02发布

问题:

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);