Error using inner matrix dimensions must agree перевод

Как я могу решить эту ошибку MATLAB «Размеры матрицы должны согласовываться»? Я набираю код для класса, но каждый раз, когда запускаю функцию, получаю ту же ошибку: Я знаю, что проблема в простой ошибке индекса, но нигде не могу ее найти. Кто-нибудь может мне помочь? Также у меня такая же проблема со следующей строкой кода: […]

Содержание

  1. Как я могу решить эту ошибку MATLAB «Размеры матрицы должны согласовываться»?
  2. 2 ответы
  3. Сложение и вычитание матриц
  4. Векторное произведение и транспонирование матриц
  5. Произведение матриц
  6. Inner matrix dimensions must agree. Индексирование (Subscripts)
  7. Error using ./ Matrix dimensions must agree
  8. 3 Answers 3
  9. Related
  10. Hot Network Questions
  11. Subscribe to RSS
  12. 5 Common MATLAB Error Messages and How to Fix Them
  13. 1. Error using * Inner matrix dimensions must agree.
  14. 2. Index exceeds matrix dimensions.
  15. 3. Subscript indices must either be real positive integers or logicals.
  16. 4. The expression to the left of the equals sign is not a valid target for an assignment.
  17. 5. Subscripted assignment dimension mismatch.
  18. Feedback
  19. How can I solve this MATLAB «Matrix dimensions must agree» error?
  20. 2 Answers 2

Как я могу решить эту ошибку MATLAB «Размеры матрицы должны согласовываться»?

Я набираю код для класса, но каждый раз, когда запускаю функцию, получаю ту же ошибку:

Я знаю, что проблема в простой ошибке индекса, но нигде не могу ее найти. Кто-нибудь может мне помочь?

Также у меня такая же проблема со следующей строкой кода:

РЕДАКТИРОВАТЬ № 1:

x2 определяется как 0:0.1:5 и y1 определяется как -5:0.1:5 , но это то, что мне было поручено определить их как. И я знаю, что exp — это не функция, потому что я использовал его в другом месте своего файла.

РЕДАКТИРОВАТЬ № 2:

OK. Итак, если я не могу использовать свои текущие x и y, могу ли я определить их так, чтобы они оставались на этих границах, при этом делая их одинакового размера?

задан 09 марта ’11, 17:03

2 ответы

ОБНОВИТЬ:

Хорошо, теперь, когда вы подтвердили, что ваши переменные x2 и y1 содержат разное количество элементов, у вас есть несколько вариантов на выбор:

Для каждой переменной вы можете создать заданное количество значений в соответствующих диапазонах с помощью функции ЛИНСПЕЙС. Например:

Однако, когда вы вычисляете результат f32 (который также будет массивом из 101 элемента), он будет оцениваться только для соответствующих пар значений в x2 и y1 (например x2(1) и y1(1) , x2(50) и y1(50) И т.д.).

Если вы предпочитаете оценивать f32 at каждую уникальная пара точек в диапазонах x2 и y1 , вы должны вместо этого использовать функцию МЕШГРИД для создания ваших ценностей. Это также позволит вам иметь разное количество точек в диапазонах для x2 и y1 :

Вышеупомянутое создаст x2 и y1 как массивы 101 на 51, такие что f32 также будет массив 101 на 51, оцениваемый во всех точках в заданных диапазонах значений.

Предыдущий ответ:

Первое, что нужно проверить, — все ли переменные, которые вы вводите в уравнение, имеют одинаковый размер или скалярные значения, которые должны быть, поскольку вы используете поэлементные операторы, такие как .^ и .* . Для первого уравнения посмотрите, какой результат вы получите, когда сделаете это:

Если они дают одинаковый результат, либо одно из них [1 1] , значит, это не твоя проблема.

Следующее, что нужно проверить, — затеняли ли вы EXP функцию, создав переменную по имени exp . Если вы запускаете код как сценарий в командном окне, введите whos и посмотрите, есть ли переменная с именем exp появляется. Если это так, вам нужно удалить или переименовать его, чтобы вы могли использовать функция ОПЫТ.

Источник

Сложение и вычитание матриц

Сложение и вычитание матриц определяется как и для массивов, то есть поэлементно. Эти операции требуют чтобы обе матрицы имели одинаковую размерность, или одна из них была скаляром (в последнем случае MATLAB прибавляет (или вычитывает) данный скаляр из всех элементов матрицы). Если размерности матриц не совпадают, в командное окно выдается со-общение об ошибке (красным цветом)

Matrix dimensions must agree.

Векторное произведение и транспонирование матриц

Вектор-строка и вектор-столбец могут быть перемножены в любом порядке (оператор умно-жения * расположен на верхнем регистре клавиши с цифрой 8). Результатом будет или ска-ляр (внутреннее произведение) или матрица (внешнее произведение). Для приведенных выше векторов v и u имеем :

Для действительных матриц, операция транспонирования меняет взаимное местоположение элементов aij aji, симметричных относительно главной диагонали. Для обозначения транс-понирования MATLAB использует одиночную кавычку (апостроф) (‘). Для нашей симметри-чной матрицы Паскаля A’ = A. Однако матрица В не является симметричной и поэтому:

Транспонирование превращает вектор-строку в вектор-столбец и наоборот. Если x и y оба яв-ляются действительными векторами, то произведение x*y не определено, но оба произве-дения x’*y и y’*x дают один и тот же скаляр. Это соотношение используется так часто, что имеет три различных имени: скалярное произведение, внутреннее произведение и точечное произведение.

Для комплексного вектора или матрицы, z, величина z’ обозначет комплексно-сопряженное транспонирование. В MATLAB-е предусмотрены также поэлементные операции над элеме-нтами массивов. Признаком поэлементных операций служит точка после обозначения пере-менной. Так, транспонирование элементов матрицы z как массива чисел обозначается z.’, по аналогии с другими операциями на массивами чисел. Например, если

тогда как z.’ есть

Для комплексных векторов, два скалярных произведения x’*y и y’*x комплексно сопряжены, а скалярное произведение x’*x комплексного вектора с самим собой есть действительное число.

Произведение матриц

Для произведения двух совместимых А и В матриц в MATLAB–е достаточно записать в ко-мандной строке С = А*В . MATLAB самостоятельно проверит совместимость размерностей матриц и выдаст результат. Если матрицы несовместимы, выдается сообщение об ошибке:

Inner matrix dimensions must agree. Индексирование (Subscripts)

Для краткого рассмотрения некоторых основных понятий, связанных с индексированием дву-мерных массивов (матриц), введем «волшебную» матрицу 4-го порядка:

Элемент в i-ой строке и j-ом столбце матрицы F обозначается через F (i,j). Например, F (4,2) есть число в четвертой строке и втором столбце. Для нашего волшебного квадрата, F(4,2) есть 14. Таким образом, можно вычислить сумму элементов четвертого столбца матрицы F, напечатав

но, как мы увидим в дальнейшем, не является самым элегантным способом суммирования элементов одного столбца.

Имеется также возможность обращения к элементам матрицы при помощи одного индекса, F(k). Это обычный способ обращения к элементам векторов (строк или столбцов). Но в MATLAB-е такой способ индексирования можно применить и к двумерным (в общем случае – многомерным) матрицам, так как система MATLAB хранит все многомерные массивы чи-сел в виде одного длинного вектора-столбца, сформированного из столбцов исходной матри-цы. Так, для нашего волшебного квадрата, F (8) есть другой способ обращения к начени 14 хранящемуся в F (4,2).

Если вы попытаетесь использовать элемент, находящийся вне размеров матрицы, это приве-дет к сообщению об ошибке

Источник

Error using ./ Matrix dimensions must agree

i’m trying to plot this code , with t,x,l variables .

i’m getting this error «Error using ./ Matrix dimensions must agree.

Error in Uentitled5 (line 16) a=cos(Lambda1.*(x./L));»

3 Answers 3

The three vectors you are using, x , t , and L must have the same number of elements. You can fix this manually by changing the step size you are using, i.e.

Another way to define vectors that explicitly defines the number of elements is `linspace’. You might use:

This will give you 1001 points for each vector in the ranges specified.

Yes, that is because L is 1×334 and x is 1×1001. To divide element by element they need to have the same number of elements.

x stores 0 to 100 at increments of 0.1
L stores 0 to 100 at increments of 0.3
So number of elements in L is less than the number of elements in x if x has the elements x = and L = , then x./L is supposed to give
ans = . If the number of elements in numerator and denominator arrays are not the same then Matlab will give an error

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

5 Common MATLAB Error Messages and How to Fix Them

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:

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.

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:

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!

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:

To fix this all you need to do is use == instead:

This code outlines the differences between the two operators more clearly:

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:

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:

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:

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.

Источник

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.

Источник

На чтение 5 мин. Просмотров 32 Опубликовано 15.12.2019

Проект:Информационные технологии
В Википедии есть портал «Компьютерные технологии»

Эта статья тематически связана с Проектом:Информационные технологии, целью которого является создание качественных и информативных статей на темы, связанные с информационными технологиями. Если вы хотите помочь проекту, то можете отредактировать статью , к которой относится это обсуждение, или посетить страницу проекта, где сможете, помимо прочего, присоединиться к проекту и принять участие в его обсуждении.

. Эту статью ещё никто не оценил по шкале оценок статей Проекта:Информационные технологии.

Источник: Это практически дословный перевод с английской статьи. OKr 10:52, 10 Ноя 2004 (UTC)

у меня возникает следующая ошибка при использовании одного из примеров в Matlab 7.0

Warning: Matrix dimensions must agree, not rendering mesh.

Warning: Matrix dimensions must agree, not rendering mesh.

Warning: Matrix dimensions must agree, not rendering mesh.

Исправил код в тексте

n=100; k=1:n-1; a=0; b=3; del=(b-a)/n; x=a+del*k; fun=@(x)(x./(1+x.^2)); y=fun(x); I=(sum(y)+(fun(a)+fun(b))/2)*del; I0=1/2*log(10); de=(1-I/I0) %% n=100; k=1:n; a=0; b=10; del=(b-a)/n; x=a+del*(k-1/2); fun=@(x)(x./(1+x.^2)); y=fun(x); I=(sum(y))*del; I0=1/2*log(10); de=(1-I/I0) %% I=quad(fun,a,b); de=(1-I/I0) %% ezplot(fun,[0,10]) hold on

%% int=cumsum(y)*del; plot(x,int); hold on %% dif=diff(y)*del; x1=( +x(n-1:end))/2 plot(x,dif); hold on 80.250.160.252 12:22, 5 апреля 2012 (UTC)mmm

—Dstary 09:13, 17 марта 2010 (UTC) n=100; k=1:n-1; a=0; b=3; del=(b-a)/n; x=a+del*k; fun=@(x)(x./(1+x.^2)); y=fun(x); I=(sum(y)+(fun(a)+fun(b))/2)*del; IO=1/2*log(10); del=(1-I/IO) 80.250.160.252 11:57, 5 апреля 2012 (UTC) (подробнее ↗)

Содержание

  1. Литератуа [ править код ]
  2. 2 Answers 2
  3. How to Get Best Site Performance

Литератуа [ править код ]

Вызывает некоторые подозрения то, что большинство книг в литературе от одного автора. Похоже на рекламу (ch3k1s7 22:09, 20 февраля 2010 (UTC)) по матлабу мало литературы на русском языке — в основном все дьяконов да потемкин 91.220.220.243 06:00, 22 февраля 2013 (UTC)

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.

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.

У меня есть матрица A 1000×1000 (содержащая значения от 0 до 150) и вектор B. 181×1. В моей матрице A я хочу сохранить только те значения, которые присутствуют в B, сохраняя при этом размер A того же размера. Я пробовал использовать функцию ismember, но она не дает ожидаемого результата. Итак, я попробовал другую функцию Вот что я делаю как код

A=A.*intersect(A,B,'stable');

Но у меня есть эта ошибка

Error using  .* 
Matrix dimensions must agree.

Как я могу решить проблему?

2 ответа

Лучший ответ

Все, что вам нужно, это ismember для этой задачи выполните следующее:

A = A.*ismember(A,B);
% ismember(A,B) gives the logical matrix containing 1's for the indexes whose values 
% are present in `B` and 0's for all other indexes. When this logical matrix is 
% element-wise multiplied with A, all the indexes of A whose elements are not in B 
% become zero 

Почему ваш код не работает?

Это связано с тем, что intersect (A, B, 'stable'), Вы получаете вектор столбца, содержащий (наиболее вероятно) меньше или (очень менее вероятно) равное количеству элементов A. Даже если оно равно, вы получите ту же ошибку, если вы умножите ее поэлементно на A, поскольку A не является вектором столбца. Поэлементное умножение требует, чтобы порядок обеих матриц был одинаковым, потому что только тогда каждый элемент матрицы может быть умножен на соответствующий элемент в другой матрице.

Код, который я показал выше с ismember, позаботится об этом, как уже объяснялось в комментариях.


2

Sardar Usama
1 Мар 2017 в 12:07

Создайте две матрицы A и B со случайными числами. C — это массив со значениями, которые находятся как в A, так и в B, используя ismember, мы можем выбрать, какие значения в A сохранить.

A = randi([0 150], 1000, 1000);
B = randi([0 150], 181, 1);
C = intersect(A, B, 'stable');
A(~ismember(A, C)) = 0;


1

Jørgen
1 Мар 2017 в 10:45

На чтение 5 мин. Опубликовано 15.12.2019

Проект:Информационные технологии
В Википедии есть портал «Компьютерные технологии»

Эта статья тематически связана с Проектом:Информационные технологии, целью которого является создание качественных и информативных статей на темы, связанные с информационными технологиями. Если вы хотите помочь проекту, то можете отредактировать статью , к которой относится это обсуждение, или посетить страницу проекта, где сможете, помимо прочего, присоединиться к проекту и принять участие в его обсуждении.

. Эту статью ещё никто не оценил по шкале оценок статей Проекта:Информационные технологии.

Источник: Это практически дословный перевод с английской статьи. OKr 10:52, 10 Ноя 2004 (UTC)

у меня возникает следующая ошибка при использовании одного из примеров в Matlab 7.0

Warning: Matrix dimensions must agree, not rendering mesh.

Warning: Matrix dimensions must agree, not rendering mesh.

Warning: Matrix dimensions must agree, not rendering mesh.

Исправил код в тексте

n=100; k=1:n-1; a=0; b=3; del=(b-a)/n; x=a+del*k; fun=@(x)(x./(1+x.^2)); y=fun(x); I=(sum(y)+(fun(a)+fun(b))/2)*del; I0=1/2*log(10); de=(1-I/I0) %% n=100; k=1:n; a=0; b=10; del=(b-a)/n; x=a+del*(k-1/2); fun=@(x)(x./(1+x.^2)); y=fun(x); I=(sum(y))*del; I0=1/2*log(10); de=(1-I/I0) %% I=quad(fun,a,b); de=(1-I/I0) %% ezplot(fun,[0,10]) hold on

%% int=cumsum(y)*del; plot(x,int); hold on %% dif=diff(y)*del; x1=( +x(n-1:end))/2 plot(x,dif); hold on 80.250.160.252 12:22, 5 апреля 2012 (UTC)mmm

—Dstary 09:13, 17 марта 2010 (UTC) n=100; k=1:n-1; a=0; b=3; del=(b-a)/n; x=a+del*k; fun=@(x)(x./(1+x.^2)); y=fun(x); I=(sum(y)+(fun(a)+fun(b))/2)*del; IO=1/2*log(10); del=(1-I/IO) 80.250.160.252 11:57, 5 апреля 2012 (UTC) (подробнее ↗)

Содержание

  1. Литератуа [ править код ]
  2. 2 Answers 2
  3. How to Get Best Site Performance

Литератуа [ править код ]

Вызывает некоторые подозрения то, что большинство книг в литературе от одного автора. Похоже на рекламу (ch3k1s7 22:09, 20 февраля 2010 (UTC)) по матлабу мало литературы на русском языке — в основном все дьяконов да потемкин 91.220.220.243 06:00, 22 февраля 2013 (UTC)

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.

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.

Понравилась статья? Поделить с друзьями:
  • 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