Ошибка matrix dimensions must agree

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.

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

This is Newton Raphsons Method for systems. Row 1 and 2 in f= [x1 etc is 2 equations for 2 circles, and I want to find 2 intersections between these circles. I have already plotted and got guess 1 = [51 28] and 2 [41 47]. I need to find 2 x1, and x2 values who solves the system.

if true

format short e, format compact

disp(‘ x f(x) h=Jf(x)’);

x=[51 28]’; %Startvektor

h=x;

iter=1;

while ( (norm(h,inf) > 1.0e-10*norm(x,inf)) & (iter < 20)),

f =[x(1).^2 + x(2).^2 -2*93*x(1) -2*63*x(2)+ 9.5820e+03

x(1).^2 + x(2).^2 -12*x(1) -32*x(2)- 1.8332e+03 ];

%Jacobian

J=[2*x(1)-2*93 2*x(2)-2*63

2*x(1)-12 2*x(2)-32];

h =-Jf;

disp(iter)

disp([x f h])

x=x+h; iter=iter+1;

end

format long

x

% code

end

Error using + Matrix dimensions must agree. Error in uppg6aNRAP (line 20) x=x+h; iter=iter+1;

PLS HELP! I’m a beginner

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

So I’m working on a function that will receive inputs from from a user-defined structure to plot an ellipsoid, but Matlab keeps spitting out this error. Here’s the portion I’m having trouble with:

theta = 0:(0.1):2*pi;
phi = 0:(0.1):pi;
a1 = ellipsoid_in(1).major_axis;
b1 = ellipsoid_in(1).minor_axis;
c1 = ellipsoid_in(1).transverse_axis;

x1 = a1*sin(phi)*cos(theta);
y1 = b1*sin(phi)*sin(theta);
w1 = c1*cos(phi);
plot3(x1,y1,w1)
grid on
hold on
x2 = x1;
y2 = y1;
w2 = w1;
plot3(x2,y2,z2)
xx = [x1;x2];
yy = [y1;y2];
ww = [w1;w2];

The error is occurring in my first (x1) equation and I’ve already tried using the .* operator on them all with the same result. I’m guessing the problem is coming from the 1×2 structure I’m calling, but I don’t know how to fix it. The variables for the structures all correspond to scalars. Any help is much appreciated.

asked Sep 12, 2014 at 2:00

harbingeroftuna's user avatar

4

theta = 0:(0.1):2*pi;
phi = 0:(0.1):pi;

With the above two lines, you’ve created two vectors. These are different lengths (since one goes to pi and the other to 2*pi, by the same step size.

You do want to use element-wise multiplication (.*), but you need your vectors to be the same lengths… otherwise, which elements get multiplied together?

answered Sep 12, 2014 at 2:20

tmpearce's user avatar

tmpearcetmpearce

12.4k4 gold badges42 silver badges60 bronze badges

0

MATLAB is a powerful programming tool that is used for validating algorithms and drawing data points or represent data sets. Developed by MathWorks, the MATLAB language is mostly used in data analysis, matrix manipulation, graphical model construction, and more.

However, once in a while, users find themselves facing an error in MATLAB. One such error is the inner matrix dimensions must agree that occurs when there is a mismatch in the array dimensions. Usually, this occurs when two matrices (arrays) with different sizes are involved in an operation.

In this documentation, we will provide a step-by-step approach to understanding and rectifying the error: inner matrix dimensions must agree.

What causes the «Inner Matrix Dimensions Must Agree» error?

The «Inner Matrix Dimensions Must Agree» error occurs when two matrices (arrays) of different sizes are being used in an operation. The error is an indication that the operation is invalid.

One of the major causes of the error is an incorrect syntax or function call, primarily during matrix manipulation or division.

How to fix the «Inner Matrix Dimensions Must Agree» error

The «Inner Matrix Dimensions Must Agree» error can be fixed by ensuring that the matrix sizes are the same or compatible in the operation. Here are the steps you can take to fix the error:

  1. Ensure that both sides of the operation are the same size
  2. Use the same syntax and functions for both sides
  3. Take extra care to check the syntax in both sides and make necessary corrections
  4. Converting a scalar to a matrix of the same size as the other matrix can sometimes be helpful
  5. Read the documentation and other related sources carefully to get an idea of what is expected

FAQs

How do I know if the matrices are of compatible sizes?

You can know if two matrices (arrays) are of compatible sizes if both matrices have the same number of elements and the same number of columns and rows.

How can I convert a scalar to a matrix?

You can convert a scalar to a matrix with the MATLAB repmat() command. You can specify the size of the matrix you want as the second parameter in the command.

What are the different types of errors that occur in MATLAB?

The MATLAB language has many different types of errors. Some of them are:

  • Variable name errors
  • Type mismatch errors
  • File input/output errors
  • Syntax errors
  • Matrix dimension must agree error
  • Floating-point errors
  • Range errors

What is the best way to debug an error in MATLAB?

The best way to debug an error in MATLAB is to use the MATLAB debugger. This allows you to step through your code line-by-line to identify the source of the error. You can also use the MATLAB debugger to inspect variables and understand how they are related to the error.

How can I learn more about the inner matrix dimensions must agree error?

MATLAB has an extensive documentation library that has detailed information about the inner matrix dimensions must agree error. You can also find plenty of tutorials and related resources online to help you understand the error.

  • How to use the MATLAB Repmat Function

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.

Plotting and taking derivatives of functions in Matlab is perfectly easy. First you just need to use the symbolic math capabilities:

syms t;
x = t*exp(-3*t)+0.25*exp(-3*t);
xdot = diff(x,t,1)
xddot = diff(x,t,2)

Then to plot these you have several options. You can substitute in numeric values using subs, which automatically vectorizes your equations so you don’t need to worry about adding .*:

t_ = 0:0.01:3;
x_ = subs(x,t,t_);
xdot_ = subs(xdot,t,t_);
xddot_ = subs(xddot,t,t_);
plot(t_,x_,'b',t_,xdot_,'g',t_,xddot_,'r')

Or you can use the ezplot function to directly plot the symbolic function over a range:

subplot(131);
ezplot(x,[0 3]);
subplot(132);
ezplot(xdot,[0 3]);
subplot(133);
ezplot(xddot,[0 3]);

The function fplot is another option if you convert your symbolic equations to numeric functions. This can be done manually or via the matlabFunction function:

subplot(131);
fplot(matlabFunction(x),[0 3])
subplot(132);
fplot(matlabFunction(xdot),[0 3])
subplot(133);
fplot(matlabFunction(xddot),[0 3])

Below two options that will do it. In the first you create a loop around your whole approach and as filenames is zero when there is no dcm file the loop will not get executed. The second option tests whether files is empty and if so it is not executed.

clear all;
close all;
clc;
fileFolder = fullfile(pwd, 'series 8');
files = dir ( fullfile (fileFolder, '*.dcm'));
fileNames = {files.name};

%examine file header (metadata , from dicom stack)

for i=length(fileNames):-1:1
   if (i == 1)
       info = dicominfo(fullfile(fileFolder,fileNames{i}));

       %extract size info from metadata
       voxelsize = [info.PixelSpacing;info.SliceThickness];

       %read one file to get size
       I = dicomread(fullfile(fileFolder,fileNames{i}));
       classI = class(I);
       sizeI = size(I);
       numImages = length(fileNames);

       %read slice images populate 3d matrix
       hWaitBar = waitbar(0,'reading dicom files');

       %create array
       mri= zeroes(info.rows , info.columns , numImages , classI );
   else
       fname = fullfile(fileFolder, fileNames{i});
       mri(:,:,i) = unit16(dicomread(fname));
       waitbar((length(fileNames)-i+1)/length(fileNames))
   end
end
delete(hWaitBar);

the second

clear all;
close all;
clc;
fileFolder = fullfile(pwd, 'series 8');
files = dir ( fullfile (fileFolder, '*.dcm'));
fileNames = {files.name};

%examine file header (metadata , from dicom stack)
if ~isempty(files)
    info = dicominfo(fullfile(fileFolder,fileNames{1}))

    %extract size info from metadata
    voxelsize = [info.PixelSpacing;info.SliceThickness];

    %read one file to get size
    I = dicomread(fullfile(fileFolder,fileNames{1}))
    classI = class(I);
    sizeI = size(I);
    numImages = length(fileNames);

    %read slice images populate 3d matrix
    hWaitBar = waitbar(0,'reading dicom files');

    %create array
    mri= zeroes(info.rows , info.columns , numImages , classI )
    for i=length(fileNames):-1:1
        fname = fullfile(fileFolder, fileNames{i});
        mri(:,:,i) = unit16(dicomread(fname));
        waitbar((length(fileNames)-i+1)/length(fileNames))
    end

    delete(hWaitBar);
end

I get this error when I run demToyUnsupervised. When I tried to debug, I found that the dimensions actually don’t agree.

Error using  * 
Inner matrix dimensions must agree.

Error in ppcaEmbed (line 50)
    X = Ycentre*u(:, 1:dims)*diag(1./sqrt(v(1:dims)));

Error in vargplvmCreate (line 109)
    X = initFunc(model.m, q);

Error in vargplvmEmbed (line 67)
model = vargplvmCreate(latentDim, d, Y, options);

Error in hsvargplvmModelCreate (line 164)
                curX = [curX initFunc(m{i}, Q1, initXOptions{h}{:})];

Error in demToyHsvargplvm1 (line 101)
model = hsvargplvmModelCreate(Ytr, options, globalOpt, initXOptions);


Error in demToyUnsupervised (line 38)
demToyHsvargplvm1; % Run the actual demo

Error in tutorial (line 39)
demToyUnsupervised; % Call to the demo

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.

Понравилась статья? Поделить с друзьями:
  • Ошибка marblebeard sea of thieves
  • Ошибка mapi 0x80040107
  • Ошибка lsu samsung 4200 устранить самостоятельно
  • Ошибка lsu hsync
  • Ошибка ls 0021 эпик геймс