Connect 2 points in matrix

5 visualizaciones (últimos 30 días)
df df
df df el 24 de Jul. de 2016
Editada: Walter Roberson el 25 de Nov. de 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

Respuestas (3)

Image Analyst
Image Analyst el 24 de Jul. de 2016
Editada: Image Analyst el 24 de Jul. de 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 el 23 de Nov. de 2017
Editada: Walter Roberson el 25 de Nov. de 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 comentario
Jan
Jan el 25 de Nov. de 2017
Editada: Jan el 25 de Nov. de 2017
I assume if x(1)<(end) should be if x(1)<x(end) .

Iniciar sesión para comentar.


Walter Roberson
Walter Roberson el 24 de Jul. de 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.

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by