代码之家  ›  专栏  ›  技术社区  ›  KGB91

在具有不同间隔的循环中使用for

  •  0
  • KGB91  · 技术社区  · 7 年前

    我有一个for循环测试函数的最大值:

    function Start
    max_i = 0;
    max_j = 0;
    max_value = 0;
    for i =1:3500
       for j = 1:3500
          new_value = CalcUFamily(i,j);
          if new_value > max_value;
             max_value = new_value;
             max_i = i;
             max_j = j;
          end
      end
    end
    max_i
    max_j
    end
    
    function uFamily = CalcUFamily(hh,hw) %h = male, w = wife
    (code)
    end
    

    我的代码运行得很好,只是因为它运行了1250000次,所以运行时间太长。因此,我想将测试间隔从1缩短到10,甚至可能是100 for 代码,还是我必须重写它?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Sardar Usama    7 年前

    重塑 CalcUFamily 使用 colon reshape )和使用 max max_value )及其线性指数。现在使用 ind2sub 将此线性索引转换为等效行( hh max_i )和列( hw max_j

    [max_value, max_Ind] = max(CalcUFamily(:));
    [hh, hw] = ind2sub(size(CalcUFamily), max_Ind);
    
        2
  •  0
  •   KGB91    7 年前

    我自己找到了一个解决方案!:)

    max_hh = 0;
    max_hw = 0;
    max_value_hhhw = -50000;
    max_value_u = -50000;
    
    hh = 1;
    hw = 1;
    runs = 0;
    interval = 10;
    datestr(clock)
    
    while hw < 3501
        while hh  < 3501 %runs hh to all posible values
            new_value = CalcUFamily(hh,hw);
            if new_value > max_value_u
                max_value_hhhw = [hh hw]; %working hour husband, working hour wife, and its utility value
                max_value_u = new_value;
            end 
            hh = hh + interval;
            runs = runs + 1; % number of runs
        end
        hh = 1;
        hw = hw + interval;
    end
    runs
    datestr(clock)
    max_value_hhhw