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

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

尚未输入任何标签。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by