# How to loop over a function again?

11 views (last 30 days)
Hari on 25 Oct 2016
Answered: indu on 28 Sep 2017
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.
Guillaume on 25 Oct 2016
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.

Ganesh Hegade on 25 Oct 2016
Edited: Ganesh Hegade on 25 Oct 2016
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.
Ganesh Hegade on 25 Oct 2016
I Think the size of shortestpaths and totalCosts are not equal. Store output of loop in an cell array and check, else put a break point atbefore end of function and check whether dimensions of ShortestPath and TotalCost are equal. Size of these 2 matrix should be equal.
Hari on 25 Oct 2016
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 on 25 Oct 2016
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

indu on 28 Sep 2017
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 .