在matlab中,我们尝试创建逻辑表,并且我们有一个名为“ functionNot”的函数,该函数将0变成1,将1变成0;
function functionNot(x)
for x >=0 && x <= 2
if x == 0
disp(1);
elseif x == 1
disp(0);
else disp (2);
end
end
end
并且我们要创建一个表,对于该表,我们有3个数组X,Y和AND结(保留“ functionNot”的值)我们有数组X和数组Y
x=[1; 1 ;1; 0; 0; 0; 2; 2; 2];
y=[1; 0; 2 ;1; 0; 2; 1; 0; 2];
tnot(x) =[ functionNot(x(1)); functionNot(x(2));functionNot(x(3));functionNot(x(4));functionNot(x(5));functionNot(x(6));functionNot(x(7));functionNot(x(8));functionNot(x(9))]
tand(x,y) =[ functionAnd(x(1),y(1));
T= table(x, y, tnot(x));
但是它总是抛出错误“输出参数过多”,任何人都知道如何解决此问题?
您遇到的问题是由于以下事实:函数x
中的functionNot
仅适用于标量,而不适用于向量。要解决此问题,您可以尝试
function y = functionNot(x)
y = x;
for k = 1:length(x)
if x(k) == 0
y(k) = 1;
elseif x(k) == 1
y(k) = 0;
else
continue;
end
end
end
此外,您也可以像下面这样编写functionNot
的矢量化版本
function y = functionNot(x)
y = 1*(x==0)+0*(x==1) + 2*(x~=0&x~=1);
end
x==0
返回逻辑向量,true
仅出现在值是0
的位置(类似于x==1
和x~=0&x~=1
)那么我认为T= table(x, y, tnot(x))
会很好用。