# How to loop over a function again?

조회 수: 42(최근 30일)
Hari 2016년 10월 25일
답변: indu 2017년 9월 28일
I have a pre-written function in matlab which is of the form : function [shortestPaths, totalCosts] = kShortestPath(netCostMatrix, source, destination, k_paths) [K-Shortest Path- Yen's algorithm by Meral Sh.] How to make this function loop for a number of 'sources' and 'destinations' without manually giving in the input each time. I tried something like this:
function loop(N)
global netCostMatrix
for ii = 1:N
for iii=1:N
source = ii;
destination = iii;
[sii,tiii] = kShortestPath(netCostMatrix, source, destination,3);
end
end
function [shortestPaths, totalCosts] = kShortestPath(netCostMatrix, source, destination, k_paths)
%...... the code for kshortest path comes here.....
end
This doesn't seem to work. Also, the variables in each iteration should be combined and listed as 2 column matrix - with shortest paths in one and total costs in other. Thank you for your time and help.
##### 댓글 수: 1표시숨기기 없음
Guillaume 2016년 10월 25일
It's completely unrelated to the question but netCostMatrix should be an input to the loop function. There is absolutely zero reason for it to be global in the above case.

댓글을 달려면 로그인하십시오.

### 답변(3개)

편집: Ganesh Hegade 2016년 10월 25일
HI,
You are not returning any output from the function loop.
function [ShortestPath, TotalCost] = loop(N)
global netCostMatrix
for ii = 1:N
for iii=1:N
source = ii;
destination = iii;
[shortestPaths, totalCosts] = kShortestPath(netCostMatrix, source, destination,3);
ShortestPath(ii, iii)= shortestPaths;
TotalCost(ii, iii) = totalCosts;
end
end
end % loop
If the netCostMatrix is already present in the workspace then you can pass this also as input for function loop.
function [shortestPaths, totalCosts] = loop(N, netCostMatrix )
end %loop
Thanks.
##### 댓글 수: 5표시숨기기 이전 댓글 수: 4
Hari 2016년 10월 25일
Sorry I'm new to MATLAB. When I checked using 'whos' function this is what I got: Shortest path is having class CELL with dimension 3 x 1 and total costs is class DOUBLE with dimension 3 x 1.

댓글을 달려면 로그인하십시오.

Guillaume 2016년 10월 25일
Probably a simpler way of writing these loops would be with:
function loop(N, netCostMatrix) %where are the outputs?
%netCostMatrix shouldn't be global, passing it as input here
[source, destination] = ndgrid(1:N);
[shortestPaths, totalCosts] = arrayfun(@(src, dest) kShortestPath(netCostMatrix, src, dest, 3), 'UniformOutput', false);
end
If the outputs or kShortestPath are both scalar, then you can omit the 'UniformOutput', false
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

indu 2017년 9월 28일
i am facing the same problem.Hope you have found out the solution for the above problem.If so can you please post the answer .

댓글을 달려면 로그인하십시오.

### 범주

Find more on Loops and Conditional Statements 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!

Translated by