【问题标题】:Octave error: some elements in list of return values are undefined [duplicate]八度错误:返回值列表中的某些元素未定义[重复]
【发布时间】:2020-08-02 20:05:42
【问题描述】:

我正在使用生成器构建矩阵,我正在尝试根据其他 list_ones 中的值获取值列

list_ones=[4,3,2,1]

我希望我的输出是:

   0   0   0   1
   0   0   1   0
   0   1   0   0
   1   0   0   0

代码正确,但有这个错误:返回值列表中的某些元素未定义

function y=matrixGenerator(list_ones, size)
  List1=[];
  Linha=[];
  nl = size;
  nc = size;
  for i = 1:nl
    elem=list_ones(i);       
    for j = 1:nc      
      if (elem==j)
         M(i,j) = 1;
      else
         M(i,j) = 0;
      endif      
    end
  end
  M
endfunction

【问题讨论】:

  • 哪些元素未定义?您已经显示了您的预期输出,请同时显示您的实际输出。
  • 哦,我明白了。你用function y=matrixGenerator(...)声明函数,然后你必须使用变量y作为输出。由于您创建矩阵 M 作为输出,因此使用 function M=matrixGenerator(...) 声明您的函数
  • @CrisLuengo 如果我可以从其他地方重新启动我们的“matlab 标签”讨论,这是一个很好的例子,我认为删除标签是不合适的。 one-hot 编码上有大量兼容的 matlab 副本。将这个问题作为其中一个问题的副本关闭会更合适。我强烈质疑在此代码末尾仅使用endfunction 而不是end 表示用户将特别需要非matlab 兼容的解决方案...

标签: arrays matrix octave


【解决方案1】:

您可以通过两种方式实现结果:

您可以使用您的matrixGenerator 方法:

function y = matrixGenerator(list_ones)
sz = length(list_ones);
y = zeros(sz, sz);
for i=1:sz
    idx = list_ones(i);
    y(i, idx) = 1;
end
disp(y)
end

输出:

     0     0     0     1
     0     0     1     0
     0     1     0     0
     1     0     0     0

或者,你可以使用built-in函数:

clear; clc

A = flip(eye(4));

disp(A)

输出:

0     0     0     1
0     0     1     0
0     1     0     0
1     0     0     0

【讨论】:

    【解决方案2】:

    也许你可以在函数matrixGenerator中试试sub2ind

    function y = matrixGenerator(list_ones)
      sz = length(list_ones)*ones(1,2);
      y = zeros(sz);
      y(sub2ind(sz,1:length(list_ones),list_ones)) = 1;
    endfunction
    

    这样

    >> matrixGenerator(list_ones)
    ans =
    
       0   0   0   1
       0   0   1   0
       0   1   0   0
       1   0   0   0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      相关资源
      最近更新 更多