Physics Forums Insights
  • Physics
    • Physics Articles
    • Physics Tutorials
    • Physics Guides
    • Physics FAQs
  • Math
    • Math Articles
    • Math Tutorials
    • Math Guides
    • Math FAQs
  • Bio/Chem/Tech
    • Bio/Chem Articles
    • Computer Science Tutorials
    • Technology Guides
  • Education
    • Education Articles
    • Education Guides
  • Interviews
  • Quizzes
  • Forums
  • Click to open the search input field Click to open the search input field Search
  • Menu Menu
matlab errors

5 Common MATLAB Error Messages and How to Fix Them

May 19, 2015/4 Comments/in Mathematics Guides/by Josh Meyer
📖Read Time: 5 minutes
📊Readability: Accessible (Clear & approachable)
🔖Core Topics: errormatrixmessagematlabcommon

In this Insight, I’ll go over 5 common MATLAB error messages, what they mean, and how to fix them. Hopefully, after reading this post you’ll find yourself being more productive, and maybe even help your friends with their code.

Most forums online where people post MATLAB questions generate quite a bit of duplicates, and PhysicsForums is no exception. The fact is, there are just certain situations that come up constantly in MATLAB, and if you’re a newer user, don’t consider yourself a programmer, or haven’t used the software in a while, then you’re likely to get tripped up and receive one of those red error messages. It can be especially frustrating when the message doesn’t make sense to you, or your best efforts to fix it come up dry.

Table of Contents

  • Error using * Inner matrix dimensions must agree
  • Index exceeds matrix dimensions
  • Subscript indices must either be real positive integers or logicals
  • The expression to the left of the equals sign is not a valid target for an assignment.
  • Subscripted assignment dimension mismatch
  • Feedback
    • More Related Articles

Error using * Inner matrix dimensions must agree

By far the most common error message I see posted about by new users is this one. They create a few matrices or vectors and just multiply them with A*B, and this message is returned. Some example code that produces this message is:

A = [1 2 3];
B = [4 5 6];
A*B
Error using * 
Inner matrix dimensions must agree.

The key to this error message is usually that people are not aware of the elementwise operators in MATLAB. The * operator performs matrix multiplication, where an NxM matrix is multiplied by an MxP matrix, resulting in an NxP matrix. Notice how those matrices have the common dimension “M”? That’s where this message comes from; it’s a common inner dimension.

Most often, you simply need to use .* instead of * to perform the elementwise multiplication, where corresponding elements are multiplied and the result is the same size as the inputs.

A.*B

ans =

     4    10    18

For more information about the different MATLAB operators, see Array vs. Matrix Operations. Note that even though this error message is the most common in this situation (since, well, multiplication is pretty popular) there are similar messages for the misuse of ^,   /, and     as opposed to .^, ./, and   ..

Index exceeds matrix dimensions

Quite simply, this error arises when you try to reference an element that doesn’t exist. For example, if the matrix has N elements, and you try to index into the N+1 element:

A = magic(5)
A =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

A(26)
Index exceeds matrix dimensions.

To fix this error, double-check that the matrix is the size you were expecting it to be and that the index you’re using is also what you expect. For example, if the index is the result of a calculation or is part of a loop, then you might need to adjust the calculation of the number of loop iterations. Some useful functions to check sizes and number of elements are numel(), size(), and length().

Subscript indices must either be real positive integers or logicals

The most common reason this message arises is that people come to MATLAB from other programming languages and can’t get used to the fact that MATLAB indexing begins at 1. A(1) is the first element in a vector or matrix (or equivalently A(1,1)), not A(0) like in other programming languages!

A = magic(3)
A =

     8     1     6
     3     5     7
     4     9     2

A(0)
Subscript indices must either be real positive integers or logicals.

There are several theories for why MATLAB uses 1-based indexing, but ultimately the answer is pretty simple. 1-based indexing is the language of Mathematics, as confirmed by Cleve Moler himself in a comment on this April Fools blog post.

We have always had BOTH 0-based indexing and 1-based indexing. In order to distinguish between the two, 0-based indices are followed by “+1″. The 1-based indices are preferred becaused they are the language of mathematics. — Cleve

I won’t expound on this anymore, but suffice it to say if you’re interested in this, a quick Google search will turn up bountiful results, as it has a long and contentious history!

This error message can also arise if you use a noninteger (or negative) value to index. What is MATLAB supposed to do with A(1.5) or A(-3)? In this context, it’s again likely that you’ll want to check the bounds of any loop statements in your code to make sure they aren’t producing decimal or negative values for indexing.

The expression to the left of the equals sign is not a valid target for an assignment.

This error message arises because of misuse of the = and == operators. The = operator does an assignment, and the == operator does a logical test for equality. In the context of an if statement, for example, the if operator is expecting to see a logical condition to determine whether to continue executing code. So the following example code produces this error:

n = 5;
if n = 4
    n = n.^2;
end
 if n = 4
      |
Error: The expression to the left of the equals sign is not a valid target for an assignment.

To fix this all you need to do is use == instead:

n = 5;
if n == 4
    n = n.^2;
end

This code outlines the differences between the two operators more clearly:

A = 1:5
A =

     1     2     3     4     5

B = 5;
A == B
ans =

     0     0     0     0     1

C = A == B
C =

     0     0     0     0     1

In short: when you need to compare values, use ==. When you want to assign a value, use =.

Subscripted assignment dimension mismatch

This error message arises because of an attempt to assign a vector or matrix into a compartment that it does not fit in. The dimension of the subscripted elements does not match the dimension of the assignment. For example, you cannot assign the first element in a matrix to be a vector, because there is only room for 1 element:

A = magic(3)
A =

     8     1     6
     3     5     7
     4     9     2

A(1) = [4 5 6]
Subscripted assignment dimension mismatch.

This error can be much more subtle when you’re working with large matrices or loops, and it can occur because of a mismatch on either side of the equals sign. Sometimes the size of a vector or matrix can grow unexpectedly in a loop, and you’ll receive this message and wonder what went wrong. The best way to debug this error is to double-check that all of your assignments are the sizes you expect them to be and that your matrices are growing (or not) as you expect them to.

If you don’t have any loops, just break the statement apart and check the size of each side. You won’t get this error if the sizes match exactly:

size(A(1:3))
ans =

     1     3

size([4 5 6])
ans =

     1     3

A(1:3) = [4 5 6]
A =

     4     1     6
     5     5     7
     6     9     2

Feedback

I could go on with another 25 error messages, but I think these are the most common ones I see people posting about. If you’re interested in reading about some others, check out this link:

http://en.wikibooks.org/wiki/MATLAB_Programming/Error_Messages

Post about your favorite or least favorite MATLAB error messages in the comments, and let me know what you think!

Disclaimer: All views and/or opinions expressed in this post are my own, and should not be interpreted in any other way.
Josh Meyer

Josh received a BA in Physics from Clark University in 2009, and an MS in Physics from SUNY Albany in 2012. He currently works as a technical writer for MathWorks, where he writes documentation for MATLAB.

More Related Articles

  • All About the Einstein Field Equations
    Tags: errors, MATLAB
    Share this entry
    • Share on Facebook
    • Share on X
    • Share on WhatsApp
    • Share on LinkedIn
    • Share on Reddit
    • Share by Mail
    https://www.physicsforums.com/insights/wp-content/uploads/2015/05/matlaberrors.png 135 240 Josh Meyer https://www.physicsforums.com/insights/wp-content/uploads/2019/02/Physics_Forums_Insights_logo.png Josh Meyer2015-05-19 14:40:462026-02-16 16:15:355 Common MATLAB Error Messages and How to Fix Them
    You might also like
    mistakes moments Frequently Made Errors in Mechanics: Moments
    2D Animation Particle in a Box: 1D & 2D Quantum Visualizations
    natural language errors Frequently Made Errors in Probability: Conditionals in Natural Language
    forces mistakes Frequently Made Errors in Mechanics: Forces
    errors springs Frequently Made Errors in Mechanics: Springs
    heat errors Frequently Made Errors in Heat: Elementary Level
    4 replies
    1. traique says:
      May 19, 2016 at 4:41 pm

      Good one!

      Log in to Reply
    2. kreil says:
      May 19, 2016 at 4:41 pm

      “FUN must be a function, a valid string expression, or an inline function object.”

      Good one! This message is returned by some functions that accept a function handle as an input if you don’t specify it correctly.

      (You might recall that function handles are the current standard, and they replaced inline function objects several years ago)

      Here is an example of a way this message can arise using FMINSEARCH and how to fix it:

      [URL]http://www.mathworks.com/matlabcentral/newsreader/view_thread/166230[/URL]

      Log in to Reply
    3. SivaChinna says:
      May 26, 2015 at 5:32 pm

      FUN must be a function, a valid string expression, or an inline function object.

      Log in to Reply
    4. Greg Bernhardt says:
      May 19, 2015 at 2:55 pm

      Great resource! Members feel free to add your own error messages you come across often!

      Log in to Reply

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply Cancel reply

    You must be logged in to post a comment.

    Trending Articles

    • What Thermodynamics and Entropy Means
    • Derivation of Gauss’s Law: Coulomb to Flux Explained
    • Impedance in AC Circuits: Definition & Key Equations
    • P vs. NP and what is a Turing Machine (TM)?
    • Why Power Determines Vehicle Acceleration Limits
    • Animal Speed Scaling: Body-Lengths per Second Across Sizes
    • Learn All About Earth’s Gravity
    • Relativity Variables: Velocity, Doppler-Bondi k, and Rapidity
    • Rindler Motion in Special Relativity: Hyperbolic Trajectories
    • Understanding Precession in Special and General Relativity

    Physics Forums

    • Classical Physics
    • Atomic and Condensed Matter
    • Quantum Physics
    • Special and General Relativity
    • Beyond the Standard Model
    • High Energy, Nuclear, Particle Physics
    • Astronomy and Astrophysics
    • Cosmology
    • Other Physics Topics

    Receive Insights Articles to Your Inbox

    Enter your email address:

    Blog Information

    • Become a Member!
    • Write for Us!
    • Table of Contents
    • Blog Author List

    Popular Topics

    astronomy (17) black holes (17) classical physics (35) cosmology (16) education (23) electromagnetism (19) general relativity (19) gravity (24) interview (21) mathematics (39) mathematics self-study (21) Physicist (26) programming (18) Quantum Field Theory (31) quantum mechanics (36) quantum physics (24) relativity (40) Special Relativity (16) technology (19) universe (21)
    2026 © Physics Forums, ALL RIGHTS RESERVED - Contact Us - Privacy Policy - About PF Insights
    • Link to X
    • Link to Facebook
    • Link to LinkedIn
    • Link to Youtube
    Link to: Frequently Made Errors in Mechanics: Hydrostatics Link to: Frequently Made Errors in Mechanics: Hydrostatics Frequently Made Errors in Mechanics: HydrostaticshydrostaticsLink to: Frequently Made Errors in Mechanics: Momentum and Impacts Link to: Frequently Made Errors in Mechanics: Momentum and Impacts impact errorsFrequently Made Errors in Mechanics: Momentum and Impacts
    Scroll to top Scroll to top Scroll to top