How to loop over a function again?
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Guillaume
am 25 Okt. 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.
Antworten (3)
Ganesh Hegade
am 25 Okt. 2016
Bearbeitet: Ganesh Hegade
am 25 Okt. 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.
5 Kommentare
Ganesh Hegade
am 25 Okt. 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.
Guillaume
am 25 Okt. 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
0 Kommentare
indu
am 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 .
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!