vertical dimensions mismatch (1x2 vs 1x1)

I am trying to make a simple replacement

my code is the following :

grad_f = @(x) [4*x(1).^3 - 8*x(2).*x(1) + 2*x(1) -2;-4*x(1).^2 + 8*x(2)];
x = [3;3]

it gives me the following: error: vertical dimensions mismatch (1x2 vs 1x1)


  • Within square brackets (the concatenation operator), elements separated by either a comma or a space are concatenated horizontally. This is an unfortunate choice, as it leads to unexpected errors. Always being consistent with spacing around operators (either never use them, or always use them on both sides) will avoid most of these unexpected errors.

    For example:

    [a - 2] % 1x1 array
    [a -2]  % 1x2 array, same as [a, -2]
    [a-2]   % 1x1 array

    This is what is happening in your code:

    grad_f = @(x) [… + 2*x(1) -2; …];

    Either put a space on both sides of the minus operator, or on neither side.