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!