【发布时间】:2020-11-19 09:54:18
【问题描述】:
我的以下代码现在太慢了,我正在寻找更好的方法来编写它。
此代码是包含 for 循环 t=1:T 的更长代码的一部分,因此以下代码针对每个 t 运行。
我有 F 公司,它们生产 Yd。他们在每个时期 t 购买一定数量的机床 K,其生产率由 A 给出;因此,在 t 中购买的机床的生产能力等于 AK=A.*K。企业的总生产能力等于总和(AK)。由于 sum(AK) 可能大于他们想要生产的 Yd,考虑到他们首先开始使用效率最高的机床(那些具有最高的 A)。因此,从产量最高的机器开始,如果某台机器的生产能力低于 Yd,则该机器的 omega 将设置为 1,如果生产能力已经达到 Yd,则该机器的 omega 将设置为 0 , 否则 omega 将被设置为所需的分数。我该如何编码?
这是我做的,但肯定太慢了:
T=100;
F=50;
A=rand(T,F); %initialized randomly (not as in my real code)
K=rand(T,F); %idem
AK=A.*K; %productivity of machine tools
Yd=rand(1,F); %initialized randomly
omega=zeros(T,F); %needs to be computed
OAK(:,:)=zeros(T,F); %needs to be computed
for f=1:F
[A_sorted_value,A_sorted_index]=sort(A(:,f)); %sort machines according to their productivity level
while sum(A_sorted_value)>0 && sum(OAK(1:t,f))<Yd(f) %apply rule as long as there are machines available and desired production has not been achieved
v=A_sorted_index(end); %pick the best machine of capital, i.e. highest productivity A
if AK(v,f)+sum(OAK(1:t,f))<=Yd(f) %assign omega=1 if existing capacity is below desired production
omega(v,f)=1;
OAK(v,f)=omega(v,f).*AK(v,f); %update existing capacity
elseif AK(v,f)+sum(OAK(1:t,f))>Yd(f) && Yd(f)>sum(OAK(1:t,f)) %assign omega so that machine v can fill desired production
omega(v,f)=(Yd(f)-sum(OAK(1:t,f)))/AK(v,f);
OAK(v,f)=omega(v,f).*AK(v,f);
end
A_sorted_index(end)=[]; %remove machine v from the list and pick the next one if condition "while" is satisfied
A_sorted_value(end)=[]; %otherwise go to the next firm
end
end
我希望它是清楚的,并提前感谢!
【问题讨论】:
标签: performance matlab loops nested-loops