0

in matlab we try to make a table for logic, and we have a function called "functionNot" which turn 0's into 1 and 1's into 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

and we want to make a table, for table we have 3 arrays X,Y, AND tnot ( which keeps value of "functionNot") and we have array X and array 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));

but it always throwing error "Too many Output Arguments" anyone know how to fix this ?

Emir Kutlugün
  • 349
  • 1
  • 6
  • 18
  • 1
    Of course there are too many output arguments, as you haven't assigned any to the function. All that your function does is display 0, 1 or 2, which is *display*, not *output*. Read the [documentation on `function`](https://mathworks.com/help/matlab/ref/function.html) to learn about function declarations – Adriaan Apr 17 '20 at 11:12
  • Additionally, a `for` loop with a logical statement as indices is ... odd to say the least. `while` loops and `if` statements go with logical values, whereas `for` loops usually accept an array to iterate over. Also, unless `x` is integer, be careful of [floating point round off](https://stackoverflow.com/q/686439/5211833) when comparing brutally with `==` without any form of tolerance. – Adriaan Apr 17 '20 at 11:19
  • `tand(x,y) =[ functionAnd(x(1),y(1));` won't work neither as there is a closing bracket missing.... – max Apr 17 '20 at 11:26

1 Answers1

2

The problem you encountered is due to the fact that x in function functionNot is only available for a scalar, rather than a vector. To fix it, you can try

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

Also, you can write a vectorized version of functionNot like below

function y = functionNot(x)
  y = 1*(x==0)+0*(x==1) + 2*(x~=0&x~=1);
end

where x==0 returns the logic vector, and trues appear only at the positions where the values are 0 (similarly to x==1 and x~=0&x~=1) then I think T= table(x, y, tnot(x)) will work well.

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Even though this may help, it's highly preferable to tell the OP (and anyone else reading this in the future) **why** this works. Especially given that the OP is doing a lot of things which aren't normal in MATLAB, they can use some training. – Adriaan Apr 17 '20 at 15:33
  • @Adriaan Thanks. I updated my answer for more details – ThomasIsCoding Apr 17 '20 at 19:08