How can I solve this MATLAB “Matrix dimensions must agree” error?

前端 未结 2 1765
北恋
北恋 2021-01-21 12:27

I am typing some code for a class but every time I run the function I get the same error:

??? Error using ==> plus
Matrix dimensions must agree.

Error in ==&         


        
相关标签:
2条回答
  • 2021-01-21 12:54

    UPDATE:

    OK, now that you have confirmed that your variables x2 and y1 contain different numbers of elements, you have a couple of solutions to choose from:

    1. For each variable, you can create a set number of values over the respective ranges using the function LINSPACE. For example:

      x2 = linspace(0,5,101);   %# 101 values spanning the range 0 to 5
      y1 = linspace(-5,5,101);  %# 101 values spanning the range -5 to 5
      

      However, when you compute the result f32 (which will also be a 101-element array), it will only be evaluated at the respective pairs of values in x2 and y1 (e.g. x2(1) and y1(1), x2(50) and y1(50), etc.).

    2. If you would rather evaluate f32 at every unique pair of points over the ranges of x2 and y1, you should instead use the function MESHGRID to generate your values. This will also allow you to have a different numbers of points over the ranges for x2 and y1:

      [x2,y1] = meshgrid(0:0.1:5,-5:0.1:5);
      

      The above will create x2 and y1 as 101-by-51 arrays such that f32 will also be a 101-by-51 array evaluated at all the points over the given ranges of values.

    Previous answer:

    The first thing to test is if all the variables you are putting into the equation are the same size or scalar values, which they would have to be since you are using element-wise operators like .^ and .*. For the first equation, see what output you get when you do this:

    size(x2)
    size(y1)
    

    If they give the same result, or either is [1 1], then that's not your problem.

    The next thing to check is whether or not you have shadowed the EXP function by creating a variable by the name exp. If you're running the code as a script in the command window, type whos and see if a variable named exp shows up. If it does, you need to delete or rename it so that you can use the function EXP.

    0 讨论(0)
  • 2021-01-21 12:54

    How do you expect -x2.^2-y1.^2 to work when x2 and y1 is of different size? x2=0:0.1:5 has fifty or so entires while y1=-5:0.1:5 has a hundred or so entries.

    0 讨论(0)
提交回复
热议问题