2012-06-05 92 views
0

我是Matlab新手,現在正在學習基本語法。Matlab函數調用基本函數

我寫的文件GetBin.m:

function res = GetBin(num_bin, bin, val) 
if val >= bin(num_bin - 1) 
    res = num_bin; 
else 
    for i = (num_bin - 1) : 1 
     if val < bin(i) 
      res = i; 
     end 
    end 
end 

和我把它叫做:

num_bin = 5; 
bin = [48.4,96.8,145.2,193.6]; % bin stands for the intermediate borders, so there are 5 bins 
fea_val = GetBin(num_bin,bin,fea(1,1)) % fea is a pre-defined 280x4096 matrix 

它會返回錯誤:

Error in GetBin (line 2) 
if val >= bin(num_bin - 1) 

Output argument "res" (and maybe others) not assigned during call to 
"/Users/mac/Documents/MATLAB/GetBin.m>GetBin". 

有誰告訴我什麼這裏錯了嗎?謝謝。

回答

2

您需要確保通過代碼的每條可能路徑都將值分配給res

對你來說,這看起來並非如此,因爲你有一個循環:

for i = (num_bins-1) : 1 
    ... 
end 

該循環永遠不會重複(因此它的值永遠不會分配給res)。您需要明確指定,它是一個遞減循環:

for i = (num_bins-1) : -1 : 1 
    ... 
end 

欲瞭解更多信息,請參見colon operator的文檔。

0
for i = (num_bin - 1) : -1 : 1