Home Visualize the path on the 2D square

# Visualize the path on the 2D square

mertbasturk
1#
mertbasturk Published in 2017-12-07 23:11:27Z
 I want to visualize all of the paths on 2D square in matlab. This code gives me the following figure which consists of a 2D square and randomly distributed of 1 and 0. https://i.hizliresim.com/Ey4G4D.png Each 1's must connected with lines from top to bottom. If there is 1, then there is a way and I have to plot line. Otherwise therre is no way and stop. Without the boundary elements, there are 3 way for each elements. Each element can go left side, right side or down side. The top left hand corner's element can go right and down direction. The top right hand corner's element can go left and down direction. This is the algorithm of the modelling. https://i.hizliresim.com/Dy0z0y.jpg How can I write this code ? I am waiting your advise :)
Georg W.
2#
Georg W. Reply to 2017-12-08 11:03:00Z

## Problem analysis

To get an information on the possible paths in your matrix/image you can use the diff function. It calculates the difference between two neighbouring matrix elements along the specified dimension. The conditions for the existence of a path are:

1. The difference between the element and its neighbour must be 0
2. The element itself must be 1

## Solution

The following matlab program will create 3 matrices containing the value 1 or true for each element with a path existing to its neighbour.

matrix = logical([1 1 1 1 0; ...
1 1 0 1 1; ...
0 0 0 1 0; ...
0 0 1 1 0])

hasPathtoRight = false(size(matrix));
hasPathtoRight(:,1:end-1) = (diff(matrix,1,2)==0) & (matrix(:,1:end-1)==1)

hasPathtoLeft = false(size(matrix));
hasPathtoLeft(:,2:end) = (diff(matrix,1,2)==0) & (matrix(:,2:end)==1)

hasPathDown = false(size(matrix));
hasPathDown(1:end-1,:) = (diff(matrix,1,1)==0) & (matrix(1:end-1,:)==1)


## Result

The result for the example matrix is shown here:

matrix =

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

hasPathtoRight =

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

hasPathtoLeft =

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

hasPathDown =

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


You can use these matrices to draw the paths in a graphical display.

 You need to login account before you can post.
Processed in 0.298769 second(s) , Gzip On .