Ошибка матлаб matrix dimensions must agree

Alexander Babayi

Please note that I have tried using » .* » instead of » * » and it STILL doesn’t work. That is the fix that every single similar question has gotten. Afterwards, it just says MATRIX dimensions must agree instead of INNER MATRIX dimensions must agree. Below is my script:

g = 9.81; t = [15:15:75]; x = [0:5:80]; v = 28; yo = 0;

y = (tan(t))*x — (g/(2*v^2*(cos(t))^2))*x^2 + yo;

It is supposed to generate results that are assembled in an array where the first dimension (rows) corresponds to the x values, and the second dimension (columns) corresponds to the t values. What should I go about doing in order to fix this error of matrix dimensions?

Accepted Answer

Stephen23

Your question states that 1st dim should correspond to the x, and the 2nd dim to t. But where are you specifying that? Both x and t are row vectors (and of different lengths), so neither of them specify anything along the 1st dim:

>> size(t)

ans =

1 5

>> size(x)

ans =

1 17

Multiply two row vectors of different lengths will be an error, no matter how many different matrix multiply methods you try:

>> tan(t)*x

??? Error using ==> mtimes

Inner matrix dimensions must agree.

>> tan(t).*x

??? Error using ==> times

Matrix dimensions must agree.

There is no standard mathematical definition for multiplying row vectors of different lengths. In this example, what should the 4 multiply with?:

>> [1,2,3,4].*[5,6,7]

??? Error using ==> mtimes

Inner matrix dimensions must agree.

Instead of imagining what the code should be doing, try to pay attention to what the code is really doing. For example, when you read about matrix multiplication then you would realize that you can trivially orient the x as a column, and you get a matrix output when it is multiplied with the row vector t:

>> x(:)*tan(t)

ans =

0 0 0 0 0

-4.28 -32.027 8.0989 1.6002 -2.1035

-8.5599 -64.053 16.198 3.2004 -4.207

-12.84 -96.08 24.297 4.8006 -6.3105

And then this leads directly to one simple solution to your question:

>> g = 9.81;

>> t = 15:15:75;

>> x = 0:5:80;

>> v = 28;

>> yo = 0;

>> y = x(:)*tan(t) — (x(:).^2) * (g./(2*v^2*(cos(t)).^2)) + yo

y =

0 0 0 0 0

-4.551 -38.6 7.5321 1.4278 -2.2876

-9.644 -90.348 13.931 2.5107 -4.9434

-15.279 -155.24 19.196 3.2487 -7.9673

-21.456 -233.28 23.327 3.6419 -11.359

-28.175 -324.47 26.325 3.6903 -15.12

-35.436 -428.81 28.189 3.3937 -19.248

-43.239 -546.29 28.92 2.7524 -23.745

-51.585 -676.92 28.517 1.7661 -28.61

-60.472 -820.7 26.981 0.435 -33.843

-69.901 -977.63 24.311 -1.241 -39.444

-79.872 -1147.7 20.508 -3.2618 -45.414

-90.386 -1330.9 15.571 -5.6275 -51.751

-101.44 -1527.3 9.5002 -8.338 -58.457

-113.04 -1736.8 2.2961 -11.393 -65.531

-125.18 -1959.5 -6.0416 -14.794 -72.973

-137.86 -2195.3 -15.513 -18.539 -80.784

Multiplying vectors (and matrices) is covered quite well in thousands of online high-school math tutorials, so there is no point in repeating it all here. Writing code without understanding what it is doing is a guarantee that the code will be buggy.


More Answers (1)

Jang geun Choi

I think, if your ‘y’ is vary with two independent variables, x and t, you should make not one dimensional vector domain but two dimensional matrix domain.

In order to make the matrix domain, you can use ‘meshgrid’ function.

g=9.81;

t=[15:15:75];

x=[0:5:80];

v=28;

yo=0;

[xm,tm]=meshgrid(x,t);

y=(tan(tm)).*xm-(g./(2.*v^2.*(cos(tm)).^2)).*xm.^2+yo;

pl=plot(x,y);

legend(pl,num2str(t’,‘t=%2.0f’))

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
clc; clear all;
N=10000; % число реализаций
del=1/2; % интервал дискретизации
T=2.5; % длительность реализаций
a=2;
b=4/2*pi;
t=0:del:T;
r=2*exp(-t)-exp(-2*t); % функция корреляции
n=length(t); % число отсчётов
for i=1:n
for j=1:n
b(i,j)=r(abs(i-j)+1);
end
end
BB=b; % исходная корреляционная матрица
D=inv(BB); % матрица точности
 
B=inv(D); % аппроксимирующая корреляционная матрица
 
 
% блоки матрицы точности
D11=[D(1,1) D(1,2) D(1,3)
D(2,1) D(2,2) D(2,3)
D(3,1) D(3,2) D(3,3)];
D21=[D(4,1) D(4,2) D(4,3)
D(5,1) D(5,2) D(5,3)
D(6,1) D(6,2) D(6,3)];
D22=[D(4,4) D(4,4) D(4,6)
D(5,4) D(5,5) D(5,6)
D(6,4) D(6,5) D(6,6)];
 
C=-inv(D22)*D21; % матрица связи
BC=inv(D22); % корреляционная матрица
[u,v]=eig(BC);
A=u*v^(1/2)*u'; % оператор окрашивания
X=zeros(3,1);
for i=5:2:N
xx=randn(3,1); % значения белого шума
y=A*xx+C*X; % два следующих значения
x(i)=y(1);
x(i+1)=y(2);
x(i+2)=y(2);
%X=[x(i-3); x(i-2);x(i-1);x(i);x(i+1); x(i+2)]; % сдвиг значений
end
 
plot(t,b(1,:),'r',t,r)

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

I’m attempting to plot the function: f(x) = x * e^(x) * cos(x) from 0 to 2*pi. I’ve tried running:

x = 0:pi/100:2*pi;
y = x*exp(x)*cos(x)

However, every time I attempt to set y. Matlab throws me a ‘Error using *’ and says Inner matrix dimensions must agree. Any insight into why this happens?

  • matlab
  • plot

asked Oct 6, 2013 at 20:09

rmp2150's user avatar

rmp2150rmp2150

7771 gold badge11 silver badges22 bronze badges

1 Answer

You have to use .* (element-wise multiplication), not * (matrix multiplication)

answered Oct 6, 2013 at 20:13

Luis Mendo's user avatar

Luis MendoLuis Mendo

111k13 gold badges76 silver badges147 bronze badges

2

  • Yep. Very basic Matlab ;-)

    Oct 6, 2013 at 20:22

  • Clearly the people who down-voted me thought so. Anyway, thanks a lot!

    Oct 6, 2013 at 20:25

Понравилась статья? Поделить с друзьями:
  • Ошибка мк 11 game data is corrupt
  • Ошибка маткад это вычисление не приближается к решению
  • Ошибка мицубиси р0845
  • Ошибка микрофона на ноутбуке виндовс 7
  • Ошибка мицубиси паджеро спорт p1783