Connect 2 points in matrix

5 Ansichten (letzte 30 Tage)
df df
df df am 24 Jul. 2016
Bearbeitet: Walter Roberson am 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

Antworten (3)

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

Melden Sie sich an, um zu kommentieren.


Walter Roberson
Walter Roberson am 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.

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by