Connect 2 points in matrix
조회 수: 5 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (3개)
Image Analyst
2016년 7월 24일
편집: Image Analyst
2016년 7월 24일
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.
댓글 수: 0
Andrew Crawford
2017년 11월 23일
편집: Walter Roberson
2017년 11월 25일
%%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
Walter Roberson
2016년 7월 24일
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!