如何在 Octave 函数中禁用输出变量

How to disable outputting variables inside Octave function

我为 Octave 编写了自己的函数,但不幸的是,除了最终结果值之外,变量 "result" 会在每次更改时写入控制台,这是不受欢迎的行为。

>> a1 = [160 60]
a1 =

   160    60

>> entr = my_entropy({a1}, false)
result =  0.84535
entr =  0.84535

应该是

>> a1 = [160 60]
a1 =

   160    60

>> entr = my_entropy({a1}, false)
entr =  0.84535

我不明白 ~ 并且它不起作用,至少在我尝试时是这样。 代码如下:

# The main difference between MATLAB bundled entropy function
# and this custom function is that they use a transformation to uint8
# and the bundled entropy() function is used mostly for signal processing
# while I simply use a straightforward solution usefull e.g. for learning trees

function f = my_entropy(data, weighted)
  # function accepts only cell arrays;
  # weighted tells whether return one weighed average entropy
  # or return a vector of entropies per bucket
  # moreover, I find vectors as the only representation of "buckets"
  # in other words, vector = bucket (leaf of decision tree)
  if nargin < 2
    weighted = true;
  end;

  rows = @(x) size(x,1);
  cols = @(x) size(x,2);

  if weighted
    result = 0;
  else
    result = [];
  end;

  for r = 1:rows(data)

    for c = 1:cols(data) # in most cases this will be 1:1

      omega = sum(data{r,c});
      epsilon = 0;

      for b = 1:cols(data{r,c})
        epsilon = epsilon + ( (data{r,c}(b) / omega) * (log2(data{r,c}(b) / omega)) );
      end;

      if (-epsilon == 0) entropy = 0; else entropy = -epsilon; end;

      if weighted
        result = result + entropy
      else
        result = [result entropy]
      end;

    end;

  end;

  f = result;

end;

# test cases

cell1 = { [16];[16];[2 2 2 2 2 2 2 2];[12];[16] }
cell2 = { [16],[12];[16],[2];[2 2 2 2 2 2 2 2],[8 8];[12],[8 8];[16],[8 8] }
cell3 = { [16],[3 3];[16],[2];[2 2 2 2 2 2 2 2],[2 2];[12],[2];[16],[2] }

# end

在您的代码中的 result = result + entropyresult = [result entropy] 之后添加 ;,或者通常在您不想在屏幕上打印的任何分配之后。


如果由于某种原因您无法修改该函数,您可以使用 evalc 来防止不需要的输出(至少在 Matlab 中)。注意本例中的输出是以char形式得到的:

T = evalc(expression) is the same as eval(expression) except that anything that would normally be written to the command window, except for error messages, is captured and returned in the character array T (lines in T are separated by \n characters).

与任何 eval 变体一样,应尽可能避免这种方法:

entr = evalc('my_entropy({a1}, false)');

在您的代码中,您应该在第 39 行和第 41 行结束时使用分号 ;

标准输出中不显示以分号结尾的行。