Azzera filtri
Azzera filtri

How can i arrange the coordinates from a matrix ?

1 visualizzazione (ultimi 30 giorni)
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?................

Risposte (2)

Simon
Simon il 2 Set 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

Azzi Abdelmalek
Azzi Abdelmalek il 2 Set 2013
Modificato: Azzi Abdelmalek il 2 Set 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]

Community Treasure Hunt

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

Start Hunting!

Translated by