创建一个函数,它返回-1表示空矩阵,0表示标量,1表示矢量,2表示没有这些

时间:2015-05-19 11:14:54

标签: matlab

我不能使用isemptyisscalarisvector

我的代码是:

 function a = classify(x)
 b = sum(x(:));
 c = sum(b);
 if c == 0
    a = -1;
 elseif length(x) == 1
        a = 0;
 elseif length(x) > 1
        a = 1;
 else
      a = 2;
 end

输入错误:

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

上述输入的输出为1

我的自动评分机发出以下错误:

  

反馈:你的函数为参数[0 1 0 0 0 1 1;1 0 0 1 1 0 0;1 1 0 0 1 1 1;0 1 1 1 1 1 0;0 1 0 1 0 1 0;1 0 0 1 1 1 1;0 1 0 0 0 0 1]犯了错误       您的解决方案正确。

1 个答案:

答案 0 :(得分:2)

如果您被允许使用size,则可能的解决方案是

function R = classify(data)
  S = size(data);
  if any(S == 0) % There is at least one dimension that is zero
    R = -1;
  elseif all(S == 1) % All dimensions are equal to 1
    R = 0;
  elseif sum(~(S == 1)) == 1 % There is exactly one dimension that contains more than 1 element
    R = 1;
  else % There are more than 1 dimensions with more than 1 element
    R = 2;
  end
end