簡單記錄一下學習Matlab過程中的代碼。
一、01背包問題
參考資料:0-1背包問題文章來源:http://www.zghlxwxcb.cn/news/detail-588057.html
%01背包問題
clc;clear
thing=[1500;3000;2000;2000;100];thing_weight=[1;4;3;1;1]; %定義物品參數(shù)
bag=zeros(length(thing),4);[a,b]=size(bag); %創(chuàng)建矩陣
for row=1:a
for col=1:b
if row == 1 %定義第一行數(shù)據(jù)
bag(row,col) = thing(row);
else %其他行
if col>thing_weight(row) %口袋承重大于該行物品重
bag(row,col) = max(bag(row-1,col),thing(row)+bag(row-1,col-thing_weight(row)));
elseif col==thing_weight(row)
bag(row,col) = max(thing(row),max(bag(:,col)));
else %口袋承重小于該行物品重
bag(row,col) = bag(row-1,col);
end
end
end
end
disp(bag)
二、最少硬幣個數(shù)問題
參考資料:清華學霸總結(jié)的動態(tài)規(guī)劃4步曲,僅這篇動歸夠了文章來源地址http://www.zghlxwxcb.cn/news/detail-588057.html
%%最少硬幣組合
clc;clear
%%定義初始參數(shù)
coin=[2 5 7];
goal=27;
f=zeros(goal+2,1);
f(1)=inf; %正無窮大
f(2)=0;
%%遞歸
for x=3:goal+2
i=x-2;
j=x-5;
k=x-7;
if i<0
i=1;
elseif i==0
i=2;
end
if j<0
j=1;
elseif j==0
j=2;
end
if k<0
k=1;
elseif k==0
k=2;
end
f(x)=min([f(i)+1 f(j)+1 f(k)+1]);
end
n=f(end); %符合goal的最少硬幣數(shù)
disp(n)
%%查看硬幣組合情況
%定義硬幣庫
a1=ones(n,1)*2;
a2=ones(n,1)*5;
a3=ones(n,1)*7;
A=[a1,a2,a3];
while true
random_num = A(randperm(numel(A),n)); %從A中隨機取n個元素
if sum(random_num)==goal
break
end
end
disp(sort(random_num))
三、線性規(guī)劃最優(yōu)解
%水庫動態(tài)規(guī)劃
clc;clear
%每月來水量
input=[10 10 10 10 40 40 40 40 5 5 5 5];
%初始水量、最大水量、最小水量
w0=100;mx=130;mn=70;
%各月電價(水價)
f=[2;2;4;2;5;6;1;4;3;5;3;2]*-10; % *-10是為了使輸出結(jié)果更直觀;負號是為了求最大值
%水庫剩余水量應介于最大最小之間
b1=zeros(12,1);
b2=zeros(12,1);
p1=mx-w0;
p2=w0-mn;
for i=1:12
p1=p1-input(i);
p2=p2+input(i);
b1(i)=p1;
b2(i)=p2;
end
b=[b1;b2];
a1=tril(ones(12))*-1; %下三角矩陣
a2=tril(ones(12));
a=[a1;a2];
[x,y]=linprog(f,a,b,[],[],ones(12,1)*5); %求函數(shù)f最小值
disp(x)
disp(-y)
xplot=[1 2 3 4 5 6 7 8 9 10 11 12];
plot(xplot,f*-1,xplot,x,xplot,input)
xlabel('月份')
legend('電價','放水量','來水量')
到了這里,關于【Matlab】動態(tài)規(guī)劃算法代碼記錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!