How can i arrange the coordinates from a matrix ?
7 views (last 30 days)
Show older comments
Hi...... I have a matrix with ones and zeros. For reference its given below X=[0 0 0 1 0;0 0 0 1 0;0 1 1 1 0;0 1 0 0 0;0 1 0 0 0] and i have to get the coordinates in the given format. (5,2)(4,2)(3,2)(3,3)(3,4)(2,4)(1,4) So that, coordinates form a continuous pattern or a path. My question is that,Is there any Matlab algorithm for arranging the Matrix coordinates according to the pattern shown above?................
0 Comments
Answers (2)
Simon
on 2 Sep 2013
There is (to my knowlegde) no matlab function for this, but with a little sorting and geometry this is no problem.
% input matrix
X = [0 0 0 1 0;0 0 0 1 0;0 1 1 1 0;0 1 0 0 0;0 1 0 0 0];
% all filled positions in matrix
[r, c] = ind2sub(size(X), find(X));
% coordinates in 2d, sorted by row index
coord = sortrows([r, c]);
% path along coordinates
coordpath = zeros(size(coord));
% start at first coordinate
coordpath(1,:) = coord(1,:);
coord(1,:) = [];
% loop over all coordinates
for n = 2:length(r)
% vector pointing from last coordinate in path to all other coordinates
vec = coord - ones(size(coord, 1), 1) * coordpath(n-1, :);
% distance to other coordinates
dist = sqrt(sum(vec.^2, 2));
% nearest coordinate has minimum distance
nextcoord = find(min(abs(dist)) == abs(dist));
% add to path
coordpath(n,:) = coord(nextcoord, :);
% remove from coordinate list
coord(nextcoord, :) = [];
end
0 Comments
Azzi Abdelmalek
on 2 Sep 2013
Edited: Azzi Abdelmalek
on 2 Sep 2013
X=[0 0 0 1 0;0 0 0 1 0;0 1 1 1 0;0 1 0 0 0;0 1 0 0 0];
[n,m]=size(X);
a=reshape(1:n*m,n,m);
a(:,2:2:end)=flipud(a(:,2:2:end));
a=a(:);
[ii,jj]=ind2sub(size(X),a(find(ismember(a,find(X)))));
out=[ii,jj]
0 Comments
See Also
Categories
Find more on Computational Geometry in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!