getting 'output argument' error when calling function

1 回表示 (過去 30 日間)
Brinta Chowdhury
Brinta Chowdhury 2018 年 3 月 22 日
コメント済み: Brinta Chowdhury 2018 年 3 月 22 日
I have written this below function :
function [winner_index] = Auction(match_fit,match_index,cbid)
bidmax = 0;
m = match_fit;
w = match_index;
for i = 1:length(m)
bid(i) = cbid*m(i,:);
effectiveBid (i)= bid(i)+randn;
if effectiveBid(i) > bidmax
winner_index = w(i);
bidmax = effectiveBid(i);
end
end
end
Previously when I run this some times it is ok, sometime it was giving the below error " Output argument "winner_index" (and maybe others) not assigned during call to "Auction".
and now I am calling this function inside a loop. It is continuously showing the same error. I don't know why :(
[SL: edited to apply code formatting. Brinta, in the future please use the {}Code button to format your code.]

採用された回答

Steven Lord
Steven Lord 2018 年 3 月 22 日
If effectiveBid(i) > bidmax is not true during any of the iterations, the variable winner_index will never be assigned a value. When the function returns, it tries to take the value of winner_index in the function and return it as the output. But winner_index doesn't exist so MATLAB throws an error.
Define winner_index to a default value before the for loop.
  2 件のコメント
Brinta Chowdhury
Brinta Chowdhury 2018 年 3 月 22 日
Thank you.
Brinta Chowdhury
Brinta Chowdhury 2018 年 3 月 22 日
Hi Steven, I modified my function as below { function [winner_index] = Auction(match_fit,match_index,cbid) % bidmax = 0;m m = match_fit; w = match_index; for i = 1:length(m) bid(i) = cbid*m(i); effectiveBid(i)= bid(i)+randn; end [s,sortedInds] = sort(effectiveBid(:),'descend') c=sortedInds(1); winner_index=w(c); end } now it is giving below error .
Undefined function or variable 'effectiveBid'. Error in Auction (line 9) [s,sortedInds] = sort(effectiveBid(:),'descend')
May be it is some thing silly, but I cannot notice. If I run this code as a separate program it is working fine.

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2018 年 3 月 22 日
If match_fit is empty or effectiveBid(i) > bidmax is never true, the variable winner_index is not created. The output of randn can be negative.
What do you want to define as output instead in this case?
Note that length(m) is not safe, because it replies the longest dimension. Better use: size(m, 1).

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by