# Shortest Path in a 3D Matrix

14 views (last 30 days)

Show older comments

jan smith
on 2 Jun 2015

Commented: Marta Alcalde
on 28 Jun 2022

##### 4 Comments

Image Analyst
on 2 Jun 2015

### Accepted Answer

Alfonso Nieto-Castanon
on 3 Jun 2015

If you do not really care too much about the 'uniqueness' issue brought up in the comments, and just want to consider a single "straight" trajectory, you could do something like:

BW = rand([50 50 50])>.25; % your 3d matrix

i1 = [3, 2, 20]; % coordinates of initial point

i2 = [6, 10, 25]; % coordinates of end point

n = max(abs(i2-i1))+1; % number of steps

i = arrayfun(@(a,b)round(linspace(a,b,n)),i1,i2,'uni',0);

idx = sub2ind(size(BW),i{:});

sumBW = nnz(BW(idx));

disp(cell2mat(i')); % display trajectory

disp(sumBW); % display number of 1's in path

In this example, the trajectory chosen between [3,2,20] and [6,10,25] would be:

3 3 4 4 5 5 5 6 6

2 3 4 5 6 7 8 9 10

20 21 21 22 23 23 24 24 25

##### 6 Comments

Marta Alcalde
on 28 Jun 2022

### More Answers (3)

Walter Roberson
on 2 Jun 2015

##### 0 Comments

Image Analyst
on 2 Jun 2015

##### 3 Comments

Image Analyst
on 3 Jun 2015

ahmad karim
on 3 Jun 2015

Plese, i have travelling salesman cost function but its give me error when i implement it plese can any one help me ?

% cost function for traveling salesperson problem % Haupt & Haupt % 2003 function dist=tspfun(pop) global iga x y [Npop,Ncity]=size(pop); tour=[pop pop(:,1)]; %distance between cities for ic=1:Ncity for id=1:Ncity dcity(ic,id)=sqrt((x(ic)-x(id))^2+(y(ic)-y(id))^2); end % id end %ic % cost of each chromosome for ic=1:Npop dist(ic,1)=0; for id=1:Ncity dist(ic,1)=dist(ic)+dcity(tour(ic,id),tour(ic,id+1)); end % id end % ic

##### 1 Comment

Image Analyst
on 3 Jun 2015

### See Also

### Products

### Community Treasure Hunt

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

Start Hunting!