How to loop over a function again?

75 ビュー (過去 30 日間)
Hari
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
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
Ganesh Hegade 2016 年 10 月 25 日
編集済み: 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 件のコメント
Hari
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
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

indu
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 .

Community Treasure Hunt

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

Start Hunting!

Translated by