Connect 2 points in matrix

5 views (last 30 days)
df df
df df on 24 Jul 2016
Edited: Walter Roberson on 25 Nov 2017
I have matrix zeros(5,5) and i know coordinates of 2 points example: [1,1],[5,5]. And now i want to connect this 2 points to get shortest road from one point to another and get something like this in matrix:
matrix =[1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1]
I completed code for this but some points are in strange coordinates and dont fit in my algorithm. I need simple solution. I want only to write path in this matrix with value 1. In my project i have matrix 800x800. I dont know if I explained well ;p

Answers (3)

Image Analyst
Image Analyst on 24 Jul 2016
Edited: Image Analyst on 24 Jul 2016
You can use imline() if you have the Image Processing Toolbox. See attached demo. The key lines are
hLine = imline(gca);
singleLineBinaryImage = hLine.createMask();
burnedImage(singleLineBinaryImage) = 255; % Burn line into existing image.

Andrew Crawford
Andrew Crawford on 23 Nov 2017
Edited: Walter Roberson on 25 Nov 2017
%%Recreate Your Matrix: but this will work with any logical matrix with only two % 1's.
I=zeros(5);
I(1)=1;
I(end)=1;
%%Operate on binary matrix with only two true's
pts=nonzeros((1:numel(I)).*I(:)');
[x,y]=ind2sub(size(I),pts);
px = polyfit(x,y,1);
py = polyfit(y,x,1);
if x(1)<(end)
xi=x(1):x(end);
else
xi=x(1):-1:x(end);
end
if y(1)<y(end)
yi=y(1):y(end);
else
yi=y(1):-1:y(end);
end
yo=round(polyval(px,xi));
xo=round(polyval(py,yi));
xy=[[xi(:),yo(:)];[xo(:),yi(:)]];
xy=unique(xy,'rows');
idx=sub2ind(size(I),xy(:,2),xy(:,1));
I(idx)=1;
%%Display output:
figure;
imagesc(I);
  1 Comment
Jan
Jan on 25 Nov 2017
Edited: Jan on 25 Nov 2017
I assume if x(1)<(end) should be if x(1)<x(end) .

Sign in to comment.


Walter Roberson
Walter Roberson on 24 Jul 2016
If there are no obstacles, then one way to get a shortest path is:
  • if the x coordinate and the y coordinate of the target are both different than the current location, then move along the diagonal to reduce the difference in both x and y coordinates by 1
  • if only one of the x coordinate or y coordinate are different than the current location, then move along the coordinate that is different
This is not the only possible shortest path if abs(x difference) is not the same as abs(y difference), but it is easy to program.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!