Troubleshooting your M-files
If you are getting error messages or unexpected behaviors while trying to run your scripts or functions, run through the following questions:
- 1. Have you saved your file?
- 2. Do you have spaces in your file name?
- 3. Is the file located in your current directory?
- 4. Does the filename end in .m? Are you calling the file using the .m?
- 5. Are you getting the "Vectors must be the same lengths." or "Inner
- matrix dimensions must agree." messages?
- 6. Do you have any variables in your workspace that have the same name
- as a function you are trying to use?
Obviously, if you haven't named your file yet, MATLAB can't find it to run it. You also have to remember to save your file if you make any updates to it!
Make sure there are no spaces anywhere in the filename, including the names of any of the folders in which the file is located. Windows may handle spaces gracefully, but MATLAB does not!
MATLAB can't find the file if it isn't in your current directory, so check that the folder listed in the "Current Directory" bar at the top of your MATLAB window is the same folder in which your file is located.
Any file that you want MATLAB to run as a script or as a function must have the .m suffix. When you run the script or function, however, don't include the .m suffix on the file name.
If you're getting an error message telling you that vectors must be the same length, or that matrix dimensions must agree, there's a good chance you're doing some matrix math where you shouldn't be. Make sure all your *, /, and ^ have a dot before them, unless you really do mean to do matrix math with your arrays.
If that doesn't help, then maybe you accidentally missed an entry in one of your arrays. You can check the size of your vectors using the size() command. The result of this command tells you how many rows and then how many columns your array contains.
Never use a variable name that is the same as a function. If you're not sure whether a function exists, try help function, where function is the name you want to check. For example, if I create a variable in my workspace named sin, and then try to use the sine function:
sin = 5; tst = sin(2*pi)
Subscript indices must either be real positive integers or logicals. Error in ==> trouble at 53 tst = sin(2*pi)
MATLAB is unhappy with this sequence because it now thinks sin is a scalar (i.e. a 1x1 matrix), and it thinks that sin(2*pi) is trying to access the 2*pi-th value of a matrix that has only 1 entry. You can fix this with a clear sin.