Error using inner matrix dimensions must agree матлаб

Why do I get the following error message : ERROR: Inner matrix dimensions must agree.

MathWorks Support Team

Why do I get the following error message :

ERROR: Inner matrix dimensions must agree.

Accepted Answer

MathWorks Support Team

Explanation:

You are attempting to perform a matrix operation, which requires certain matrix dimensions to agree, on matrices that do not satisfy this requirement.

Common causes:

You are attempting to multiply or divide two matrices where the number of columns in the first is not equal to the number of rows in the second (for *) or the number of rows do not match (for ). This often indicates that you are performing matrix operations when you instead intended to perform array operations.

Please refer to the attached example demonstrating this error:

MatrixDimensionsMustAgree.m

Solution:

Stop MATLAB on the line where the error occurs. Verify that you are not performing an extra transpose operation or omitting one where necessary. Also verify the sizes of the matrices, which you are multiplying or dividing, agree in the corresponding dimensions. You can do this using the Workspace browser or the SIZE function. If you intended to perform array operations instead of matrix operations, replace the *, /, , or ^ matrix operators with the .*, ./, ., or .^ array operators instead. If you pass your formula as a string to the VECTORIZE function, VECTORIZE will return the formula with the matrix operators (*, /, and ^) replaced by the array operators (.*, ./, .^).

https://www.mathworks.com/help/matlab/ref/vectorize.html


More Answers (3)

rahul patil

Error using — Matrix dimensions must agree.

Error in premnmx (line 105) tn = 2*(t-mint0*oneQ)./((maxt0-mint0)*oneQ) — 1;

Error in ssnewtest (line 9) [pn,minp,maxp,tn,mint,maxt] = premnmx(p,t)


Greg Heath

For N I-dimensional inputs paired with N O-dimensional target outputs

[ I N ] = size(input)

[ O N ] = size(target)

I always place these right after I read the data in.

Hope this help.

Thank you for formally accepting my answer


Feranmi Akanni

You get the error if you are performing matrix element wise operation without preceding the operator with dot (.).

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

1

1. 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 go to 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   ..

2. 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().

3. 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 a number of 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.

4. 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 =.

5. 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 in an unexpected way 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

Obviously, 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 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.

Содержание

  1. Getting «. Error using ==> mtimes Inner matrix dimensions must agree» error
  2. Direct link to this question
  3. Direct link to this question
  4. Answers (2)
  5. Direct link to this answer
  6. Direct link to this answer
  7. Direct link to this answer
  8. Direct link to this answer
  9. See Also
  10. Categories
  11. Community Treasure Hunt
  12. How to Get Best Site Performance
  13. Americas
  14. Europe
  15. Asia Pacific
  16. How can I solve this MATLAB «Matrix dimensions must agree» error?
  17. 2 Answers 2
  18. . Error using ==> mtimes Inner matrix dimensions must agree.Please help me get out of this error
  19. Direct link to this question
  20. Direct link to this question
  21. Answers (1)
  22. Direct link to this answer
  23. Direct link to this answer
  24. See Also
  25. Categories
  26. Community Treasure Hunt
  27. How to Get Best Site Performance
  28. Americas
  29. Europe
  30. Asia Pacific
  31. Getting «. Error using ==> mtimes Inner matrix dimensions must agree» error
  32. Direct link to this question
  33. Direct link to this question
  34. Answers (2)
  35. Direct link to this answer
  36. Direct link to this answer
  37. Direct link to this answer
  38. Direct link to this answer
  39. See Also
  40. Categories
  41. Community Treasure Hunt
  42. How to Get Best Site Performance
  43. Americas
  44. Europe
  45. Asia Pacific
  46. Getting «. Error using ==> mtimes Inner matrix dimensions must agree» error
  47. Direct link to this question
  48. Direct link to this question
  49. Answers (2)
  50. Direct link to this answer
  51. Direct link to this answer
  52. Direct link to this answer
  53. Direct link to this answer
  54. See Also
  55. Categories
  56. Community Treasure Hunt
  57. How to Get Best Site Performance
  58. Americas
  59. Europe
  60. Asia Pacific

Getting «. Error using ==> mtimes Inner matrix dimensions must agree» error

Direct link to this question

Direct link to this question

0 Comments

Answers (2)

Direct link to this answer

Direct link to this answer

0 Comments

Direct link to this answer

Direct link to this answer

  1. —> ‘u’ is intended to be a (1×1000) double vector as well, in which situation u=m.*c; (note the ‘.*’ indicating element-by-element multiplication as opposed to vector or matrix multiplication);
  2. —> ‘u’ is intended to be a (1×1) double scalar, in which situation u=m*c’; (note the transpose operator (‘) after the c , keeping m as (1×1000) double row vector and creating c to a (1000×1) double column vector.
0 Comments

See Also

Categories

Find the treasures in MATLAB Central and discover how the community can help you!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Americas

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
    • 简体中文 Chinese
    • English
  • 日本 Japanese (日本語)
  • 한국 Korean (한국어)

Accelerating the pace of engineering and science

MathWorks is the leading developer of mathematical computing software for engineers and scientists.

Источник

How can I solve this MATLAB «Matrix dimensions must agree» error?

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

I know that the problem is a simple index error, but I can’t seem to find it anywhere. Can somebody help me?

Also I’m having the same problem with the following line of code:

EDIT #1:

x2 is defined as 0:0.1:5 and y1 is defined as -5:0.1:5 , but that is what I have been assigned to define them as. And I know exp is not a function because I have used it elsewhere in my file.

EDIT #2:

OK. So if I can’t use my current x and y is there anyway I can define them to keep them on those bounds while still making them the same size?

2 Answers 2

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:

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

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.).

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 :

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:

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.

Источник

. Error using ==> mtimes Inner matrix dimensions must agree.Please help me get out of this error

Direct link to this question

Direct link to this question

0 Comments

Answers (1)

Direct link to this answer

Direct link to this answer

0 Comments

See Also

Categories

No tags entered yet.

Find the treasures in MATLAB Central and discover how the community can help you!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Americas

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
    • 简体中文 Chinese
    • English
  • 日本 Japanese (日本語)
  • 한국 Korean (한국어)

Accelerating the pace of engineering and science

MathWorks is the leading developer of mathematical computing software for engineers and scientists.

Источник

Getting «. Error using ==> mtimes Inner matrix dimensions must agree» error

Direct link to this question

Direct link to this question

0 Comments

Answers (2)

Direct link to this answer

Direct link to this answer

0 Comments

Direct link to this answer

Direct link to this answer

  1. —> ‘u’ is intended to be a (1×1000) double vector as well, in which situation u=m.*c; (note the ‘.*’ indicating element-by-element multiplication as opposed to vector or matrix multiplication);
  2. —> ‘u’ is intended to be a (1×1) double scalar, in which situation u=m*c’; (note the transpose operator (‘) after the c , keeping m as (1×1000) double row vector and creating c to a (1000×1) double column vector.
0 Comments

See Also

Categories

Find the treasures in MATLAB Central and discover how the community can help you!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Americas

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
    • 简体中文 Chinese
    • English
  • 日本 Japanese (日本語)
  • 한국 Korean (한국어)

Accelerating the pace of engineering and science

MathWorks is the leading developer of mathematical computing software for engineers and scientists.

Источник

Getting «. Error using ==> mtimes Inner matrix dimensions must agree» error

Direct link to this question

Direct link to this question

0 Comments

Answers (2)

Direct link to this answer

Direct link to this answer

0 Comments

Direct link to this answer

Direct link to this answer

  1. —> ‘u’ is intended to be a (1×1000) double vector as well, in which situation u=m.*c; (note the ‘.*’ indicating element-by-element multiplication as opposed to vector or matrix multiplication);
  2. —> ‘u’ is intended to be a (1×1) double scalar, in which situation u=m*c’; (note the transpose operator (‘) after the c , keeping m as (1×1000) double row vector and creating c to a (1000×1) double column vector.
0 Comments

See Also

Categories

Find the treasures in MATLAB Central and discover how the community can help you!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Americas

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
    • 简体中文 Chinese
    • English
  • 日本 Japanese (日本語)
  • 한국 Korean (한국어)

Accelerating the pace of engineering and science

MathWorks is the leading developer of mathematical computing software for engineers and scientists.

Источник

SNOP. 

 Re: Матлаб, решение системы линейных диффуров

Сообщение10.05.2016, 19:03 


26/04/16
11

У меня все работает.

global T E U11 U22 U21 U12 G T0 X0 A
T = 1
E = 2
U11 = 3
U22 = 4
U12 = 5
U21 = 6
G = 7
T0 = [0 1]
X0=[1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0];
A = [0*1i, 0, T, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, —2*G*1i, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    T, -T, -E-G*1i, 0, 0, 0, 0, 0, 0, 0, 0, 0, U21-U11, 0, 0, 0, 0, 0, 0, 0, 0, 0, U22-U12, 0, 0, 0, 0, 0, 0, 0, 0, 0
    -T, T, 0, E-G*1i, 0, 0, 0, 0, 0, U11-U21, 0, 0, 0, 0, 0, 0, 0, 0, 0, U21-U22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0*1i, 0, 0, 0, 0, 0, T, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, —2*G*1i, -T, T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, T, -T, -E-G*1i, 0, 0, 0, U22-U12, 0, 0, 0, 0, U21-U11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, -T, T, 0, E-G*1i, 0, 0, 0, 0, 0, 0, 0, 0, U12-U22, 0, 0, 0, 0, U21-U11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, —2*G*1i, T, T, 0, -T, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, T, E+U11-U21-G*1i, 0, T, 0, -T, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, U12-U22, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, T, 0, U22-U12-3*G*1i-E, T, 0, 0, -T, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, U21-U22, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, T, T, —2*G*1i, 0, 0, 0, -T, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, U21-E-U11-G*1i, T, T, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, U12-U22, 0, 0, 0, 0, 0
    0*1i, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, T, 0, 0, T, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, T, 0, —2*G*1i, T, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, T, T U21-U11-E-G*1i, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, U22-U12, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, E+U12-U22-3*G*1i, T, T, 0, -T, 0, 0, 0, 0, U11-U21, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, T, 2*(E+U11-U21-G*1i), 0, T, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, T, 0, —4*G*1i, T, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, T, T, E+U12-U22-3*G*1i, 0, 0, 0, -T, U11-U21, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, -T, 0, 0, 0, —2*G*1i, T, T, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, -T, 0, 0, T E+U11-U21-G*1i, 0, T, 0, U12-U22, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, -T, 0, T, 0, -E+U22-U12-3*G*1i, 0, 0, 0, U21-U11, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, -T, 0, T, T, —2*G*1i, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, E+U11+U12-U21-U22-3*G*1i, 0, 0, 0, 0, 0, -T, T
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, E+U11+U12-U21-U22-3*G*1i, 0, 0, -T, T, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, T+U21+U12-E-U11-U22-3*G*1i, 0, 0, 0, T, -T
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, U11+U22-U12-U21-E-3*G*1i, T, -T, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, T, —2*G*1i, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, T, 0, -T, 0, —4*G*1i, 0, 0
    0*1i, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, T, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, T, 0, -T, 0, 0, 0, 0, —4*G*1i];

function dX=func1(t, X)
global T E U11 U22 U21 U12 G T0 X0 A
dX=A*X;
end

ode45(@func1, T0, X0)

Да, заработало, возможно end не хватало. А не подскажете, как теперь построить только X(1)? Писать отдельную m-функцию или можно сразу после ode писать?

— 10.05.2016, 19:15 —

Решил разделить на две части:
Функцию:

function dX=func2(t, X)
global T E U11 U22 U21 U12 G T0 X0 A
dX=A*X;
end

И Решение как-то так:

T=1; E=0.21; U11=0;U21=0;U12=0;U22=0; G=0.001; T0=[0,1];
X0=[1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0];
A = [0*1i, 0, T, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, —2*G*1i, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    T, -T, -E-G*1i, 0, 0, 0, 0, 0, 0, 0, 0, 0, U21-U11, 0, 0, 0, 0, 0, 0, 0, 0, 0, U22-U12, 0, 0, 0, 0, 0, 0, 0, 0, 0
    -T, T, 0, E-G*1i, 0, 0, 0, 0, 0, U11-U21, 0, 0, 0, 0, 0, 0, 0, 0, 0, U21-U22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0*1i, 0, 0, 0, 0, 0, T, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, —2*G*1i, -T, T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, T, -T, -E-G*1i, 0, 0, 0, U22-U12, 0, 0, 0, 0, U21-U11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, -T, T, 0, E-G*1i, 0, 0, 0, 0, 0, 0, 0, 0, U12-U22, 0, 0, 0, 0, U21-U11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, —2*G*1i, T, T, 0, -T, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, T, E+U11-U21-G*1i, 0, T, 0, -T, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, U12-U22, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, T, 0, U22-U12-3*G*1i-E, T, 0, 0, -T, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, U21-U22, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, T, T, —2*G*1i, 0, 0, 0, -T, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, U21-E-U11-G*1i, T, T, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, U12-U22, 0, 0, 0, 0, 0
    0*1i, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, T, 0, 0, T, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, T, 0, —2*G*1i, T, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, T, T U21-U11-E-G*1i, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, U22-U12, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, E+U12-U22-3*G*1i, T, T, 0, -T, 0, 0, 0, 0, U11-U21, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, 0, T, 2*(E+U11-U21-G*1i), 0, T, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, T, 0, —4*G*1i, T, 0, 0, -T, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, 0, 0, T, T, E+U12-U22-3*G*1i, 0, 0, 0, -T, U11-U21, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, -T, 0, 0, 0, —2*G*1i, T, T, 0, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, -T, 0, 0, T E+U11-U21-G*1i, 0, T, 0, U12-U22, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, -T, 0, T, 0, -E+U22-U12-3*G*1i, 0, 0, 0, U21-U11, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, 0, 0, -T, 0, T, T, —2*G*1i, 0, 0, 0, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, E+U11+U12-U21-U22-3*G*1i, 0, 0, 0, 0, 0, -T, T
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, E+U11+U12-U21-U22-3*G*1i, 0, 0, -T, T, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, T+U21+U12-E-U11-U22-3*G*1i, 0, 0, 0, T, -T
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, U11+U22-U12-U21-E-3*G*1i, T, -T, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, T, —2*G*1i, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, T, 0, -T, 0, —4*G*1i, 0, 0
    0*1i, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -T, 0, T, 0, 0, 0, 0, 0
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, T, 0, -T, 0, 0, 0, 0, —4*G*1i];

ode45(@func2, T0, X0);
plot(T,X(:,1),‘x’);
grid on
xlabel(‘t’);

В результате получаю:
Error using odeplot (line 63)
Error updating the ODEPLOT window. Solution data may have been corrupted. Argument Y cannot be complex.

Error in ode45 (line 435)
stop = feval(outputFcn,tout_new,yout_new(outputs,:),»,outputArgs{:});

Error in reshenie (line 36)
ode45(@func2, T0, X0);
Что за хрень?

— 10.05.2016, 19:20 —

Можно ли сделать так, чтобы строилась только действительная часть, то есть чтобы он считал все полностью, но строил только действительную часть?

As far as I’ve seen there is little help out there to help people decipher MATLAB’s error messages. Most of the syntax errors are not difficult to fix once you know what is causing them so this is intended to be a guide to identifying and fixing errors in MATLAB code.

Warnings are also shown here as these often lead to errors later.

Arithmetic errors[edit | edit source]

Usually these are self-explanatory. As a reminder, here are some common functions that cannot be performed and what MATLAB returns (along with a warning for each one):

a/0 = Inf if a > 0, -Inf if a < 0, and NaN if a = 0.
log(0) = -Inf
MATLAB defines 0^0 to be 1.

NaN will very often result in errors or useless results unless measures are taken to avoid propagating them.

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

So check the dimensions of all the terms in your expression. Often it is an indexing mistake that causes the terms to be of different size.
If you are using power function you might add a single dot after the parameter. i.e. y=x.^2 instead of y=x^2

Matrix multiplication requires the number of columns in the first matrix to equal the number of rows in the second. Otherwise, you get the message:

??? Error using ==> mtimes
Inner matrix dimensions must agree.

Note the difference between this error and the previous one. This error often occurs because of indexing issues OR because you meant to use componentwise multiplication but forgot the dot.

Attempting to take the inverse of a singular matrix will result in a warning and a matrix of Infs. It is wise to calculate the determinant before attempting to take the inverse or, better, to use a method that does not require you to take the inverse since its not numerically stable.

Attempting to take a power of a nonsquare matrix results in the error

??? Error using ==> mpower
Matrix must be square.

This is usually because you meant to use componentwise exponentiation and forgot the dot.

Array Indexing errors[edit | edit source]

Array indexing is a key component of MATLAB. One feature is that the names of variables and functions are case sensitive, and that one can alias builtin or user-written functions with variables of the same name. So, if you make an array called abs and you try to call the function abs(1), MATLAB will return the first value in the array abs instead of the value 1. MATLAB will not return an error for this as it is not possible to know for certain that the aliasing of the function wasn’t intentional. Hence, never ever name your variables the same as an existing MATLAB function. Unfortunately, there are so many supplied functions in the base product plus installed toolboxes, remembering all of them is impossible so use which proposedname if you have any doubt the name might be in use previously before defining a new array or function. Later versions of MATLAB with the command completion feature will show the short help information after the opening parenthesis or tab-completion options, using which will aid in avoiding such errors before they arise later in execution by not creating the alias.

Some things are rather obvious but take some practice in avoiding:

You cannot try to access part of an array that does not exist yet.

>> A = [1,3];
>> A(3)
??? Index exceeds matrix dimensions.

Unfortunately, MATLAB doesn’t tell you which variable you exceeded the dimensions on if there’s more than one so you’ll have to check that. This often occurs if, for example, you are using a loop to change which part of an array is accessed, but the loop doesn’t stop before you reach the end of the array. This also happens if you end up with an empty matrix as a result of some operation and then try to access an element inside it.

You cannot try to access a negative, complex, noninteger, or zero part of an array; if you do you get this message:

>> A(-1)
>> A(i)
>> A(1.5)
>> A(0)
??? Subscript indices must either be real positive integers or logicals.

Note that MATLAB arrays are 1-based, not 0-based and are fixed lower dimension, not variable. MATLAB may be able to tell you which index is not real or logical depending on context.

 >> y=3*A(-1)
Attempted to access A(-1); index must be a positive integer or logical. 

The latter being an expression is parsed differently and so has the actual array available in the error message.

Also note that if 0 were a logical 0 (false) then the statement A(0) would not be an indexing error but a logical subscripting expression. In this case the return would be the empty [] array as there are no subscripts matching false in the defined set of [1 2] as A has been defined above. A more useful expression would be something like

>> A(A==3)

Attempting to use non-standard MATLAB syntax in your indexing will often result in the error:

>> A(2::, 2)
??? A(2::, 2)
        |
Error: Unexpected MATLAB operator.

The above could be an example of someone trying to access all rows of A after the first one and the second column, in which case you should use the «end» syntax, as in:

>> A(2:end, 2)
ans = 3

Assignment errors[edit | edit source]

Ah, assignment, that is using the = sign to give a variable, or certain elements of an array, a particular value.

Let’s start with a classic mistake:

>> a = 2;
>> if a = 3
??? if a = 3
         |
Error: The expression to the left of the equals sign is not a valid target for an assignment.

This error occurs because you meant to see if «a» equaled 3, but instead you told MATLAB to assign «a» a value of 3. You cannot do that on the same line that the if/while statement is on. The correct syntax is

>> if a == 3
>> end

This creates no errors (and you can put anything inside the conditional you want).

You cannot have a normal array with two different classes of data inside it. For example,

>> A = @(T) (1+T)
A = 
   @(T) (1+T)
>> A(2) = 3
??? Conversion to function_handle from double is not possible.

For such a purpose you should use cell arrays or struct arrays.

Here’s the tricky one. Take a look at the following code:

>> A = [1,2,3;4,5,6;7,8,9];
>> A(2,:) = [3,5];
??? Subscripted assignment dimension mismatch.
>> A(2,:) = [1,4,5,6];
??? Subscripted assignment dimension mismatch.
>> A(1:2, 1:2) = [1,2,3,4];
??? Subscripted assignment dimension mismatch.

What is happening here? In all three cases, take a look at the dimensions of the left and the right hand sides. In the first example, the left hand side is a 1×3 array but the right side is a 1×2 array. In the second, the left hand side is 1×3 while the right is 1×4. Finally, in the third, the left hand side is 2×2 while the right is 1×4. In all three cases, the dimensions do not match. They must match if you want to replace a specific portion of an existing variable. It doesn’t matter if they have the same number of data points or not (as the third example shows); the dimensions must also be the same, with the exception that if you have a 1xn array on one side and an nx1 on the other MATLAB will automatically transpose and replace for you:

>> A(2,:) = [1;2;3]
A =   1     2     3
      1     2     3
      7     8     9

If you do not want this be aware of it!

Struct array errors[edit | edit source]

Struct arrays are rather complex, and they have a rigid set of rules of what you can and can not do with them. Let us first deal with indexing within struct arrays. Suppose you define the variable «cube» and want to store the volume and the length of one side of two different cubes in a struct array. This can be done as follows:

>> cube(1).side = 1;
>> cube(1).volume = 1;
>> cube(2).side = 2;
>> cube(2).volume = 8;

This seems like a good way of storing data and it is for some purposes. However, suppose you wanted to abstract the volumes from the struct and store them in one array. You cannot do it this way:

>> volumes = cube.volume
??? Illegal right hand side in assignment. Too many elements.

You’ll notice that if you tell MATLAB to display cube.volume, it will display both values, but reassign the variable ans each time, because it is treated as two separate variables. In order to avoid the error, you must format ‘cube.volume’ as an array upon assignment.

>> volumes = {cube.volume}

You can also write in a separate assignment for each cube but this is more adaptable to larger numbers of cubes.

Just like extracting data, you must input the data one at a time, even if it is the same for all instances of the root (cube).

>> cube.volForm = @(S) (S^3)
??? Incorrect number of right hand side elements in dot name assignment.  Missing [] around left hand side is a likely cause.
>> cube(:).volForm = @(S) (S^3)
??? Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side.  Missing [] are the most likely cause.

Unfortunately missing [] is not the cause, since adding them causes more errors. The cause is that you cannot assign the same value to all fields of the same name at once, you must do it one at a time, as in the following code:

>> for ii = 1:2
>>   cube(ii).volForm = @(S) (S^3);
>> end
>> cube
ans = 1x2 struct array with fields:
  volume
  side
  volForm

The same volume formula is then found in both cubes. This problem can be alleviated if you do not split the root, which is highly recommended. For example, you can use a struct like this:

>> shapes.cubeVol = @(S) (S^3);
>> shapes.cube(1).vol = 1;
>> shapes.cube(2).vol = 8;

This avoids having to use a loop to put in the formula common to all cubes.

Syntax errors[edit | edit source]

Parenthesis errors[edit | edit source]

Unlike in C++, you are not required to terminate every line with anything but a line break of some sort. However, there are still syntax rules you have to follow. In MATLAB you have to be especially careful with where you put your parenthesis so that MATLAB will do what you want it to.

A very common error is illustrated in the following:

>> A(1
??? A(1
       |
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.

This error is simple enough, it means you’re missing a parenthesis, or you have too many. Another closely related error is the following:

>> A(1))
??? A(1))
        |
Error: Unbalanced or misused parentheses or brackets.

MATLAB tries to tell you where the missing parenthesis should go but it isn’t always right. Thus for a complex expression you have to go through it very carefully to find your typo. A useful trick is to try to set a breakpoint a line after the offending line. It won’t turn red until the error is corrected, so keep trying to correct it and saving the file until that breakpoint turns red. Of course, after this you have to make sure the parenthesis placement makes sense, otherwise you’ll probably get another error related to invalid indecies or invalid function calls.

String errors[edit | edit source]

There are two ways that you can create a string; use the ‘ string ‘ syntax, or type two words separated by only whitespace (not including line breaks), as in

>> save file.txt variable

In this line, file.txt and variable are passed to the save function as strings. It is an occasional mistake to forget a parenthesis and accidentally try to pass a string to a function that does not accept strings as input:

>> eye 5
??? Error using ==> eye
Only input must be numeric or a valid numeric class name.

These should not be hard to spot because the string is color-coded purple. Things like this occur if you uncomment a line of text and forget to change it.

Forgetting the closing ‘ in the other syntax for a string results in an obvious error:

>> A = 'hi
??? A = 'hi
        |
Error: A MATLAB string constant is not terminated properly.

The unterminated string is color-coded red to let you know that it is not terminated, since it’s otherwise easy to forget.

A common mistake with strings is to try to compare them using the ‘==’ operator. This does not work if the strings are not the same length, because strings are arrays of characters, and to compare arrays with ‘==’ they must be the same size. To compare two strings you must use the strcmp function:

>> 'AA' == 'AaA'
??? Error using ==> eq
Matrix dimensions must agree.
>> strcmp('AA', 'AaA')
ans = 0
>> strcmp('A', 'a')
ans = 0
>> strcmp('AA', 'AA')
ans = 1

Note that MATLAB strings are case sensitive, ‘A’ and ‘a’ are not the same string.

Also beware that the ‘ character for beginning and ending strings is the same character indicating transposition. So if you close a string and don’t begin it, you will most likely end up with an error about an undefined variable (if you’re trying to transpose an undefined variable) or just get really weird results because you transposed something you didn’t intend to.

Other miscellaneous errors[edit | edit source]

You cannot leave trailing functions, and if you do MATLAB gives you an error that is similar but not exactly the same as that for a missing parenthesis, since it doesn’t want to venture a guess:

>> A = 1+3+
??? A = 1+3+
            |
Error: Expression or statement is incomplete or incorrect.

These usually are not hard to spot, and often result from forgetting the «…» necessary to split a line.

The double colon is not the only «unexpected MATLAB operator», there is also «..», «….», and several other typos that generate this error.

If you accidentally type the ` character you get the error:

>> ??? `
       |
Error: The input character is not valid in MATLAB statements or expressions.

This usually occurs because you intended to put a «1» in the equation but missed the key.
Another possibility is that you named your m-file with unusual letters for computers. Like in Germany «ä, ü or ö». Be sure to name your m-files only with usual letters and no capital letters.

Function Calling errors[edit | edit source]

It is quite possible to try to call a function that doesn’t exist, such as:

>> samplemat = [1 2; 1 4]
>> A = eigen(samplemat);
??? Undefined command/function 'eigen'.

This can happen because you do not know the name of the function that performs the operation intended (for example, if you wanted to compute the eigenvalues of matrix «samplemat», you would want to call eig, not eigen). It is often useful to pull up MATLAB’s help (go to help -> product help or type doc into the command prompt) and do a search for the operation you want.

If you’re trying to call a function you created and you get this error, there are several possible reasons:

  1. The m-file must be in one of the paths listed under file -> set path, or must be in your current directory
  2. The m-file must have the same name as the name in the function declaration. You must be aware of this especially if you change the name of your functions, you must also change the name of the file or MATLAB will not find the right function!

If MATLAB finds the function, it will attempt to run it. However, there are several potential pitfalls to avoid in calling functions. It is necessary to know the nature of the input and output arguments of a given function in order to call it. For MATLAB’s built-in functions, this information is found in the documentation, or by typing

>> help functionname

It is a good idea to set up some comments so that the help function can read them in your own code as well, so you can keep track of how all your functions work and what they do at a quick reference. To do this, note that the help function reads only the block of comments directly under the function declaration, so for example, if you write a function like this:

function outvars = myfunc(invars)
% function outvars = myfunc(invars)
% Outputs outvars
% All of this is outputted when you type >> help myfunc 

% But this wouldn't be

save the function as «myfunc.m», and type

>> help myfunc

it will output:

>> function outvars = myfunc(invars)
Outputs outvars
All of this is outputted when you type >> help myfunc

Most functions (not all however) require at least one input argument, and calling it with too few will result in an error:

>> A = ode45()
??? Error using ==> ode45
Not enough input arguments.  See ODE45.

You cannot call a function with too many input arguments either:

>> A = plus(1,2,3)
??? Error using ==> plus
Too many input arguments.

Input arguments must be in a format expected by the function. This will be very function-specific, so see the documentation or help for details on what they expect. For example, the first argument to ODE45 and other ODE solvers has to be the function handle; if you pass arguments in the wrong order you will be given an error to that effect.

You can choose how many of the output arguments you want out of those available by using the bracket notation. You can choose to save fewer outputs than the function offers, but you cannot assign more variables than the function can output:

>> A = [1,2;3,4]
D = eig(A); %one output argument
[V,D] = eig(A); %two output arguments
[V,D,Mistake] = eig(A);
??? Error using ==> eig
Too many output arguments.

All assigned output arguments must also be of the correct class if you are replacing parts of an array that already exists (see the section on assignment for more on this). If you’re creating a new variable with the output, this is not an issue.

Control Flow errors[edit | edit source]

The most common one by far is if you forget the ‘END’, which is an issue in M-file functions. It will tell you that ‘at least one END is missing’ and try to tell you where the loop or conditional statement starts.

If you have too many END statements and more than one function in an M-file, MATLAB may give you a cryptic message about not formatting the functions correctly. This is because all functions in the same M-file must either end with an END statement or not. It doesn’t matter which, but if you have too many END statements in one of the functions, MATLAB will think your function is ending early and will get confused when the next function in line does not have an END statement at the end of it. So if you get this confusing message, look for extra END statements and it should fix your problem. If the message is displayed when publishing, say to an HTML file, the problem may be an erratic hierarchical indentation. Try selecting all and then hitting cntrl-i for automatic indentation to fix the problem.

Having an extra END in a ‘switch’ statement gives a message that you used the ‘case’ keyword illegally, because MATLAB thinks you ended the switch statement early, and ‘case’ has no meaning outside a ‘switch’ statement.

Other errors[edit | edit source]

There are numerous types of errors that do not generate errors from the MATLAB compiler, which have to do with calling the wrong function, using the wrong operation, using the wrong variable, introducing an infinite loop, and so on. These will be the hardest to fix, but with the help of the MATLAB debugger, they will be easier to find. See Debugging M Files for details on how to use the debugger.

Detecting or planning an error[edit | edit source]

No matter how accurate the programming is, errors might happen.
Using debug techniques are to great help, but planning an error or expecting an error could prove to be just as valuable. This includes making a possibly unneeded if block to decide what to do. I.e. if x < 5 do this and x > 5 do something else.
Also inside the big loops add an if block with modulo, like: if not ( mod ( ii , 5 ) ) % do something; end. Now the loop only does a test for every ii counter which can be divided by 5 without any remainder after the division.
Some syntax errors or logical errors inside a loop happens after looping for a long time, if an error happens then the error message is displayed, explaining where it happened but not necessarily why it happened. I.e. vector x is one element shorter than element y, and x .* y could not happen.
This mistake often happens on the last element in the shortest vector, and is quite difficult to discover unless measures are taken. try % do something; catch me me.getReport; then a breakpoint and even disp(me.getReport) will help in this situation. If the error is not fatal the code may even continue, but instead displaying the error as a message or it could be converted to a warning.

Included Matlab tools / functions: warning, lastwarn, disp, try catch, dbstack, rethrow, throwAsCaller and Matlab help on the above functions to discover pros and cons for each method.

Понравилась статья? Поделить с друзьями:
  • Error using imhist expected input number 1 i or x to be two dimensional
  • Error using horzcat dimensions of matrices being concatenated are not consistent матлаб
  • Error username is already in use please choose another one
  • Error user with this e mail already exist
  • Error user with such email already exists