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 ?

3
  • 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 to learn about function declarations Commented Apr 17, 2020 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 when comparing brutally with == without any form of tolerance. Commented Apr 17, 2020 at 11:19
  • tand(x,y) =[ functionAnd(x(1),y(1)); won't work neither as there is a closing bracket missing.... Commented Apr 17, 2020 at 11:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 Thanks. I updated my answer for more details

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.