Error using mesh line 71 data dimensions must agree

Error using surf (line 71) Data dimensions must agree.. How to rectify 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 Products Release Community Treasure Hunt Find the treasures in MATLAB Central […]

Содержание

  1. Error using surf (line 71) Data dimensions must agree.. How to rectify this error.
  2. Direct link to this question
  3. Direct link to this question
  4. Answers (1)
  5. Direct link to this answer
  6. Direct link to this answer
  7. See Also
  8. Categories
  9. Products
  10. Release
  11. Community Treasure Hunt
  12. How to Get Best Site Performance
  13. Americas
  14. Europe
  15. Asia Pacific
  16. Data dimensions must agree error
  17. Direct link to this question
  18. Direct link to this question
  19. Direct link to this comment
  20. Direct link to this comment
  21. Direct link to this comment
  22. Direct link to this comment
  23. Answers (1)
  24. Direct link to this answer
  25. Direct link to this answer
  26. See Also
  27. Categories
  28. Community Treasure Hunt
  29. How to Get Best Site Performance
  30. Americas
  31. Europe
  32. Asia Pacific
  33. While running this program I got the error «Error using mesh (line 71) Data dimensions must agree»
  34. Direct link to this question
  35. Direct link to this question
  36. Answers (1)
  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. Surf dimensions do not agree. Help!
  47. Direct link to this question
  48. Direct link to this question
  49. Answers (1)
  50. Direct link to this answer
  51. Direct link to this answer
  52. Direct link to this comment
  53. Direct link to this comment
  54. Direct link to this comment
  55. Direct link to this comment
  56. See Also
  57. Categories
  58. Community Treasure Hunt
  59. How to Get Best Site Performance
  60. Americas
  61. Europe
  62. Asia Pacific
  63. While running this program I got the error «Error using mesh (line 71) Data dimensions must agree»
  64. Direct link to this question
  65. Direct link to this question
  66. Answers (1)
  67. Direct link to this answer
  68. Direct link to this answer
  69. See Also
  70. Categories
  71. Community Treasure Hunt
  72. How to Get Best Site Performance
  73. Americas
  74. Europe
  75. Asia Pacific

Error using surf (line 71) Data dimensions must agree.. How to rectify 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

Products

Release

Community Treasure Hunt

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.

Читайте также:  Unarc dll вернул код ошибки 6 error file read operation failed что делать

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.

Источник

Data dimensions must agree error

Direct link to this question

Direct link to this question

2 Comments

Direct link to this comment

Direct link to this comment

Direct link to this comment

Direct link to this comment

Answers (1)

Direct link to this answer

Direct link to this answer

0 Comments

See Also

Categories

Community Treasure Hunt

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 (한국어)

Читайте также:  Assistant ap 105 прошивка

Accelerating the pace of engineering and science

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

Источник

While running this program I got the error «Error using mesh (line 71) Data dimensions must agree»

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

Community Treasure Hunt

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.

Источник

Surf dimensions do not agree. Help!

Direct link to this question

Direct link to this question

0 Comments

Answers (1)

Direct link to this answer

Direct link to this answer

2 Comments

Direct link to this comment

Direct link to this comment

Direct link to this comment

Direct link to this comment

See Also

Categories

Community Treasure Hunt

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

Читайте также:  Bravis nb106 3g прошивка

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.

Источник

While running this program I got the error «Error using mesh (line 71) Data dimensions must agree»

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

Community Treasure Hunt

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.

Источник

Hozra

0 / 0 / 0

Регистрация: 02.08.2013

Сообщений: 5

1

02.08.2013, 17:01. Показов 5803. Ответов 8

Метки нет (Все метки)


Здравствуйте.

Пытаюсь построить 3-D график (2-D строится нормально). Выскакивает ошибка:

Matlab M
1
2
3
4
5
Error using  .* 
Matrix dimensions must agree.
 
Error in Untitled (line 6)
a   = 1-sqrt(1-h.*h)*exp(-2*be).*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);

Ничего криминального в 6й строке не нашел. Ошибка вылетает, когда на эту часть умножаю

Matlab M
1
((cos(2*psi)+exp(-2*ga)*cos(2*psi))

Почему при этом умножении выскакивает ошибка непонятно. Ведь в скобках нет перемножения векторов.
Помогите, пожалуйста, разобраться.

Рабочий код:

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
al=1.5e-4; be=2e-3; ga=2e-3;
ko1=2*sqrt(al);  ko2=2*sqrt(be);
 
k=ko1; h=0:0.1:1;  psi=0:0.01:5;
 
a   = 1-sqrt(1-h.*h)*exp(-2*be).*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);
b   = sqrt(1-h*h)*exp(-2*be)*((sin(2*psi)+exp(-2*ga)*sin(2*psi))/2);
f   = sqrt(1-h*h)-exp(-2*be)*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);
g   = exp(-2*be)*((sin(2*psi)+exp(-2*ga)*sin(2*psi))/2);
 
phi = 0.5*atan((a.*g-b.*f)./(a.*f+b.*g));
 
plot3(psi,psi,h),grid,xlabel('ось X'),ylabel('ось Y'),zlabel('ось Z');

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



lomt

453 / 279 / 13

Регистрация: 13.11.2012

Сообщений: 588

Записей в блоге: 1

02.08.2013, 17:24

2

Криминальность в том, что в строчке

Matlab M
1
a   = 1-sqrt(1-h.*h)*exp(-2*be).*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);

Размерность левой части 1х11, а правой 1х501, поэтому их никак не перемножить между собой.



0



0 / 0 / 0

Регистрация: 02.08.2013

Сообщений: 5

02.08.2013, 17:28

 [ТС]

3

lomt
правильно ли я понял, что в этом случае размерности должны совпадать и все??
Под другому, как мне тогда построить 10 графиков в одной плоскости? Хотелось бы конечно 3-D график построить…



0



0 / 0 / 0

Регистрация: 02.08.2013

Сообщений: 5

02.08.2013, 17:33

 [ТС]

4

Сделал размерности одинаковыми, не работает
По-моему дело в другом, наверно…



0



Зосима

5210 / 3542 / 370

Регистрация: 02.04.2012

Сообщений: 6,455

Записей в блоге: 17

02.08.2013, 19:22

5

lomt, нужно матричную магию приметить: вектор-столбец умножаемый на вектор-строку (разных размеров) дает в результате матрицу, НО нужно чтобы

вначале

был

столбец

, а после знака «умножить» —

строка

! Никак иначе! это матричное умножение, от перестановки меняется всё!
Типа такого:

Matlab M
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
>> a = 0:4
a =
     0     1     2     3     4
 
>> b = (0:0.1:1)'
b =
         0
    0.1000
    0.2000
    0.3000
    0.4000
    0.5000
    0.6000
    0.7000
    0.8000
    0.9000
    1.0000
 
>> b*a
 
ans =
         0         0         0         0         0
         0    0.1000    0.2000    0.3000    0.4000
         0    0.2000    0.4000    0.6000    0.8000
         0    0.3000    0.6000    0.9000    1.2000
         0    0.4000    0.8000    1.2000    1.6000
         0    0.5000    1.0000    1.5000    2.0000
         0    0.6000    1.2000    1.8000    2.4000
         0    0.7000    1.4000    2.1000    2.8000
         0    0.8000    1.6000    2.4000    3.2000
         0    0.9000    1.8000    2.7000    3.6000
         0    1.0000    2.0000    3.0000    4.0000

Добавлено через 9 минут

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
clear, clc
 
al=1.5e-4; be=2e-3; ga=2e-3;
ko1=2*sqrt(al);  ko2=2*sqrt(be);
 
k=ko1; h=(0:0.1:1)';  psi=0:0.01:5;
 
a   = 1 - (sqrt(1-h.^2) * (exp(-2*be).*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2)) );
b   = sqrt(1-h.^2)*exp(-2*be)*((sin(2*psi)+exp(-2*ga)*sin(2*psi))/2);
f   = sqrt(1-h.^2)*ones(size(psi)) - ones(size(h))*exp(-2*be)*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);
g   = ones(size(h))*exp(-2*be)*((sin(2*psi)+exp(-2*ga)*sin(2*psi))/2);
 
phi = 0.5*atan((a.*g-b.*f)./(a.*f+b.*g));
 
plot3(psi,psi,h),grid,xlabel('ось X'),ylabel('ось Y'),zlabel('ось Z');

Считает все, но в рисовалке что-то явно напутал.
Но вообще такие штуки делаются через meshgrid:

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
al=1.5e-4; be=2e-3; ga=2e-3;
ko1=2*sqrt(al);  ko2=2*sqrt(be);
 
k=ko1; 
[h psi] = meshgrid(0:0.1:1, 0:0.01:5);
 
a = 1-sqrt(1-h.^2).*exp(-2*be).*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);
b = sqrt(1-h.^2).*exp(-2*be).*((sin(2*psi)+exp(-2*ga)*sin(2*psi))/2);
f = sqrt(1-h.^2)-exp(-2*be).*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);
g = exp(-2*be).*((sin(2*psi)+exp(-2*ga)*sin(2*psi))/2);
 
phi = 0.5*atan((a.*g-b.*f)./(a.*f+b.*g));



1



0 / 0 / 0

Регистрация: 02.08.2013

Сообщений: 5

02.08.2013, 19:47

 [ТС]

6

Зосима

Спасибо, все работает

Что значит

Но вообще такие штуки делаются через meshgrid

?
Я так понимаю, что после meshgrid я все равно вызываю plot3.
Или в данном случае plot3 можно не использовать?

Можно ли сделать так, чтобы все кривые были соединены между собой, .т.е. получился бы этакий плавный переход.
А так на рисунке набор «сечений», вот если бы их соединить…



0



5210 / 3542 / 370

Регистрация: 02.04.2012

Сообщений: 6,455

Записей в блоге: 17

02.08.2013, 20:08

7

Цитата
Сообщение от Hozra
Посмотреть сообщение

Что значит:Но вообще такие штуки делаются через meshgrid

Это типичный прием при построении функции двух преременных в матлаб мы вначале создаем cразу две матрицы h и psi, затем что-то считаем, а потом строим результат, и красота такого подхода в том, что не надо скурпулезно выполнять правила матричного умножения (обрати внимание на мой первый вариант, в некоторых местах, чтобы получить нужный размер, мне приходилось домножать на вспомогательный массив из единиц ones(size(h))), а входные данные и результат при этом получаются все одного размера!

Цитата
Сообщение от Hozra
Посмотреть сообщение

Можно ли сделать так, чтобы все кривые были соединены между собой, .т.е. получился бы этакий плавный переход.
А так на рисунке набор «сечений», вот если бы их соединить…

Тут тебе должна помочь функции mesh или surf:
mesh(h,psi,phi) или surf(h,psi,phi)
*единственное, не знаю что от чего строится, поэтому может переменные надо переставить местами.



0



Hozra

0 / 0 / 0

Регистрация: 02.08.2013

Сообщений: 5

04.08.2013, 22:32

 [ТС]

8

Зосима

Все понял, второй подход мне понравился
С первым вариантом мозг поломал, учитывая, что Матлаб недавно изучаю.
Все заработало, в целом разобрался.

Добавлено через 4 часа 18 минут
Хм. Появилась ошибка другого плана. После подсчета phi необходимо подсчитать и построить график для соответствующих комплексных чисел. Вот полный код:

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
al=1.5e-4; be=2e-3; ga=2e-3;
ko1=2*sqrt(al);  ko2=2*sqrt(be);
 
k=ko1; 
[h psi] = meshgrid(0:0.1:1, 0:0.1:5);
 
a = 1-sqrt(1-h.^2).*exp(-2*be).*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);
b = sqrt(1-h.^2).*exp(-2*be).*((sin(2*psi)+exp(-2*ga)*sin(2*psi))/2);
f = sqrt(1-h.^2)-exp(-2*be).*((cos(2*psi)+exp(-2*ga)*cos(2*psi))/2);
g = exp(-2*be).*((sin(2*psi)+exp(-2*ga)*sin(2*psi))/2);
 
phi = 0.5*atan((a.*g-b.*f)./(a.*f+b.*g));
 
c  = a-sqrt(1-k.^2).*sqrt(1-h.^2).*exp(-2*al).*cosd(2*psi)+sqrt(1-k.^2).*exp(-2*al-2*be)*((cosd(2*(phi+psi))+exp(-2*ga)*cosd(2*(phi+psi)))/2);
d  = b+sqrt(1-k.^2).*sqrt(1-h.^2).*exp(-2*al).*sind(2*psi)-sqrt(1-k.^2).*exp(-2*al-2*be)*((sind(2*(phi+psi))+exp(-2*ga)*sind(2*(phi+psi)))/2);
 
b2  = (i*k*(a+b*i))/(c+d*i);  % комплексное
b4  = (-k.*h.*exp(-al-phi*i))./(c+d*i);  % комплексное
 
surf(psi,abs(b2),h);

Ошибка:

Matlab M
1
2
3
4
5
Error using surf (line 75)
Data dimensions must agree.
 
Error in Untitled11 (line 24)
surf(psi,abs(b2),h);

Когда я выравниваю размерности h и psi, тогда ошибка исчезает, но график при этом строится некорректно. До этого проблем с размерностями не было.

В чем может быть проблема?



0



5210 / 3542 / 370

Регистрация: 02.04.2012

Сообщений: 6,455

Записей в блоге: 17

04.08.2013, 22:52

9

Точку перед делением в строке 17 не забыл? Забыл!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

04.08.2013, 22:52

Помогаю со студенческими работами здесь

Ошибка при построении графика
здравствуйте. подскажите пожалуйста в чем ошибка, почему то не считает строчку p. clc
clear all

Ошибка при построении графика
Схема, используемая мною для построения графиков по точкам так, чтобы линия была плавной,…

Ошибка при построении графика
Здравствуйте. У меня возникает ошибка, длинная, при построении графика. Вот код. Помогите,…

Ошибка при построении графика функции
надо сдеать график по функции,все переменные задал, угол a меняется от 3.6 до 360 с шагом 3.6,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

9

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.

Понравилась статья? Поделить с друзьями:
  • Error using loadlibrary matlab
  • Error using inner matrix dimensions must agree перевод
  • Error using inner matrix dimensions must agree матлаб
  • Error using inline subsref line 12 not enough inputs to inline function
  • Error using imhist expected input number 1 i or x to be two dimensional