0

I have the following loop :

for i=1:size(voisins1_TSP,1)
    cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
end

However, voisins1_Star(i,:) can be empty and MATLAB is not happy with that:

Index exceeds matrix dimensions.
Error in Mainipulation (line 38)

cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);

How would it be possible to avoid this situation?

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
MysteryGuy
  • 1,091
  • 2
  • 18
  • 43
  • https://stackoverflow.com/questions/6764062/optional-args-in-matlab-functions – agent_bean Dec 08 '17 at 09:55
  • @rafaelgonzalez Sorry, I don't understand well how this works... Could you explain about my situation, please ? – MysteryGuy Dec 08 '17 at 10:01
  • 2
    Not having any idea what your function `CalculCost` is doing with its input noone will be able to help you with your situation ... you just need to implement the idea in rafaels link ... – Irreducible Dec 08 '17 at 10:02
  • 1
    Avoid calling `voisins1_Star(i,:)` if the element does not exist. How you should implement it depends on your actual situation, but probably involves an if-test. Please always provide a [mcve]. – m7913d Dec 08 '17 at 10:32

1 Answers1

1

You would need to post CalculCost to get a proper answer.

But going based on what you have posted, a solution to your problem is to make two functions, CalculCost and CalculCostEmpty, and put a check in the for loop:

for i=1:size(voisins1_TSP,1)
  if isempty(voisins1_TSP(i,:))
    cout(i)=CalculCostEmpty(voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
  else
    cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
  end
end
Richard
  • 256
  • 1
  • 7