Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>A = [3 8 8 8 8 8; 4 6 1 0 7 -1; 9 7 0 2 6 -1; 7 0 0 5 4 4; 4 -1 0 2 8 1; 1 -1 0 8 3 9]; test = [1 2 3; 6 5 4; 7 8 9]; %//Pad A with zeros on each side so that comparing with test never overruns the boundries %//BTW if you have the image processing toolbox you can use the padarray() function to handle this P = zeros(size(A) + 2); P(2:end-1, 2:end-1) = A; current = zeros(size(A) + 2); past = zeros(size(A) + 2); %//Initial state (starting point) current(5,5) = 1; %//This is A(4,4) but shifted up 1 because of the padding condition = 1; while sum(condition(:)) &gt; 0; %//get the coordinates of any new values added to current [x, y] = find(current - past); %//update past to last iterations current past = current; %//loop through all the coordinates returned by find above for ii=1:size(x); %//Make coord vectors that represent the current coordinate plus it 8 immediate neighbours. %//Note that this is why we padded the side in the beginning, so if we hit a coordinate on an edge, we can still get 8 neighbours for it! xcoords = x(ii)-1:x(ii)+1; ycoords = y(ii)-1:y(ii)+1; %//Update current based on comparing the coord and its neighbours against the test matrix, be sure to keep the past found points hence the OR current(xcoords, ycoords) = (P(xcoords, ycoords) == test) | current(xcoords, ycoords); end %//The stopping condition is when current == past condition = current - past; end %//Strip off the padded sides FinalAnswer = current(2:end-1, 2:end-1) [R, C] = find(FinalAnswer); coords = [R C] %//This line is unnecessary, it just prints out the results at the end for you. </code></pre> <p>OK cool you got very close, so here is the final solution with the loops. It runs in about 0.002 seconds so it's pretty quick I think. The output is</p> <pre><code>FinalAnswer = 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 1 0 0 1 0 0 1 1 1 0 0 0 0 1 0 0 0 0 0 0 1 coords = 4 1 2 2 3 2 2 3 3 4 4 4 4 5 5 5 4 6 6 6 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload