How to repeat a code and build upon previous run's results?

1 回表示 (過去 30 日間)
Garrett
Garrett 2017 年 7 月 21 日
編集済み: Sergey Kasyanov 2017 年 7 月 24 日
I have a code that runs through a matrix, finds the min, finds min of corresponding supply/demand vectors and does proper subtraction. How do I tell it to just keep looping this for x number of times or until the associated vectors all =zero.
CostsMtx=[16,18,17,20,17;25,27,29,32,28;1.5,1.6,1.7,2,1.8;50,54,56,60,57;60,63,65,68,64];
supply=[800,600,1000,400,100];
demand=[870,435,725,464,406];
mtxsz=size(CostsMtx);
%%%%%%%%%%
tmtx=CostsMtx;
res=zeros(mtxsz);
%%%%%%%%%
R=supply;
D=demand;
x=min(tmtx(tmtx>0));
[Row,Col]=find(tmtx==x);
rm=R(1,Row);
dm=D(1,Col);
if R(1,Row)==0
tmtx(Row,Col)=0;
end
if D(1,Col)==0
tmtx(Row,Col)=0;
end
if rm<dm
res(Row,Col)=tmtx(Row,Col)*R(1,Row);
D(1,Col)=D(1,Col)-R(1,Row);
R(1,Row)=0;
tmtx(Row,Col)=0;
end
if dm<rm
res(Row,Col)=tmtx(Row,Col)*D(1,Col);
R(1,Row)=R(1,Row)-D(1,Col);
D(1,Col)=0;
tmtx(Row,Col)=0;
end
%%%%%%%
display(res)

採用された回答

Sergey Kasyanov
Sergey Kasyanov 2017 年 7 月 24 日
編集済み: Sergey Kasyanov 2017 年 7 月 24 日
Try this. I hope I understand you right.
CostsMtx=[16,18,17,20,17;25,27,29,32,28;1.5,1.6,1.7,2,1.8;50,54,56,60,57;60,63,65,68,64];
supply=[800,600,1000,400,100];
demand=[870,435,725,464,406];
mtxsz=size(CostsMtx);
%%%%%%%%%%
tmtx=CostsMtx;
res=zeros(mtxsz);
%%%%%%%%%
R=supply;
D=demand;
%repeat infinum times
while true
x=min(tmtx(tmtx>0));
%if there are no any x>0 then stop repeat
if isempty(x)
break;
end
[Row,Col]=find(tmtx==x);
rm=R(1,Row);
dm=D(1,Col);
if R(1,Row)==0
tmtx(Row,Col)=0;
end
if D(1,Col)==0
tmtx(Row,Col)=0;
end
if rm<dm
res(Row,Col)=tmtx(Row,Col)*R(1,Row);
D(1,Col)=D(1,Col)-R(1,Row);
R(1,Row)=0;
tmtx(Row,Col)=0;
end
if dm<rm
res(Row,Col)=tmtx(Row,Col)*D(1,Col);
R(1,Row)=R(1,Row)-D(1,Col);
D(1,Col)=0;
tmtx(Row,Col)=0;
end
end
%%%%%%%

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

タグが未入力です。

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by