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

Using for in a loop with different intervals

我有一个 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

最基本的是它正在测试我一直试图优化的功能(在此处的一些帮助下),但到目前为止我还没有做到。因此,我想测试制作一个循环来测试所有可能的值,即丈夫和妻子的工作时间,从 1 小时到 3500 小时(每年)。然后我想从 CalcUFamily 及其对应的输入变量 hh 和 hw(在上面的函数中称为 i 和 j)获得最高效用值。

我的代码运行良好,除了 运行 需要很长时间,因为它 运行s 12 250 000 次。因此,我想将测试间隔从 1 增加到 10 甚至 100。这可以用 for 代码实现,还是我必须以某种方式重写它?

非常感谢您的帮助!

使用 colon (or reshape) and use max to find the maximum value (max_value) and its linear index. Now use ind2subCalcUFamily 重塑为向量,将此线性索引转换为等效的行(hhmax_i)和列(hwmax_j) 下标。

[max_value, max_Ind] = max(CalcUFamily(:));
[hh, hw] = ind2sub(size(CalcUFamily), max_Ind);

我自己找到了解决办法! :)

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