matlab函数调用基本

时间:2012-06-05 11:54:23

标签: 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 个答案:

答案 0 :(得分:2)

您需要确保代码中的每条可能路径都为res分配值。

在你的情况下,看起来情况并非如此,因为你有一个循环:

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

该循环永远不会迭代(因此它永远不会为res赋值)。您需要明确指定它是一个递减循环:

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

有关详细信息,请参阅colon operator上的文档。

答案 1 :(得分:0)

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