我写了这个凌乱的代码.当我使用该函数运行代码的第一部分时daa,有时会产生结果,但有时会产生错误消息.有没有人有一些想法如何纠正它?
矩形空矩阵的分配不正确.错误
daa(第26行)favoritec(i)=find(sPref(i,:)==bestmatch(i));
这是特别有问题,当我增加的维n和m
这是代码
clear all;
n=4;
m=2;
Q=[1;1];
sPref=zeros(n,m);
cPref=zeros(m,n);
for i=1:n
sPref(i,:)=randperm(m);
end
for j=1:m
cPref(j,:)=randperm(n);
end
match=daa(sPref,cPref,Q)
Run Code Online (Sandbox Code Playgroud)
然后函数daa定义如下:
function match=daa(sPref,cPref,Q)
proposition=false(size(sPref)); % keep track who has proposed to which. False= not proposed yet
match=zeros(length(sPref),1);
favoritec=zeros(length(sPref),1);
numberS=zeros(size(cPref,1),1);
bestmatch=zeros(length(sPref),1);
iter=0;
while (min(match)==0) % as long as there is one unmatched, continues the loop (except the break)
iter=iter+1;
app=find(match==0);
for i=app(1:end)'
notProposed=(proposition(i,:)==false);
bestmatch(i)=min(sPref(i,notProposed));
favoritec(i)=find(sPref(i,:)==bestmatch(i));
numberS(favoritec(i))= numberS(favoritec(i))+1; % keep track of the no.of applicants
proposition(i,bestmatch(i))=1; % propsed to college j finishes,either reject or accept
end
% college deciding...
for j=1:size(cPref,1)
S_comp=find(favoritec==j); % find the students competing for the same Favoritec
if numberS(j) <=Q(j) % sum of students at the college smaller or equal than quota
match(S_comp)=favoritec(S_comp); % accept tentative offer
numberS(j)=sum(match==j);
sPref(S_comp,j)=NaN;
else
noapl=setxor(1:length(cPref),S_comp);
cPreft=cPref(j,:); % truncated pref,change the pref of those who didn't apply to NaN
cPreft(noapl)=NaN;
[r,I]=sort(cPreft);
topq=I(1:Q(j)); % college takes the top quota q students
match(S_comp)=0; % clean the previous assignment
match(topq)= favoritec(topq);
numberS(favoritec)=Q(j);
rejapp=setxor(S_comp,topq); % the students who got rejected
sPref(rejapp,j)=NaN;
end
%display(match);
end
%% if all choices have proposed, then stop
if proposition(i,:)==true;
display('already proposed to every college')
display(i)
break
end
end
Run Code Online (Sandbox Code Playgroud)
我相信'使用矩形空矩阵进行不正确的赋值'意味着您尝试将矩形空矩阵指定给标量位置.矩形空矩阵是显示为"空矩阵:0乘1"的矩阵.产生这种矩阵的一种方法是find在矩阵上进行全部假,或者矩形空矩阵本身.
在您的代码中,发生此错误是因为没有sPref(i,:)== bestmatch(i)的实例.
如果你输入
rng(1237)
Run Code Online (Sandbox Code Playgroud)
然后执行你的代码(没有全部清除).您可以重现错误.
在调用daa之前查看变量,您可以看到daa([2, 1; 2, 1; 1, 2; 2, 1], [2, 1, 3, 4; 4, 2, 1, 3], [1;1])失败.另一个断点显示,sPref(1,:) = [2,NaN]和notProposed=[false, true]这样bestmatch(1)就是NaN-这是从来没有无所不能.这表明错误可能在于您在下一部分中分配的NaNs方式sPref.
你需要自己找到那个bug.但这应该回答你关于"错误分配"错误的问题.
这个问题应该标记为"matlab".使用您遇到问题的主要工具或语言标记您的帖子,以便合适的人阅读.
一系列简短的步骤可以让您更轻松地回答您的问题.尝试使用一些种子值rng并包含daa函数调用比使用随机数的大量步骤更好.