What line does it say the error is on? I’ll bet it’s on that line where you do a left matrix division ‘/’.
Unless you actually want to do a matrix division, a simple solution is to do a find-n-replace: «/» -> «./»
Otherwise, please format your code and, as Sean says, show which line the error occurs on. For extra credit, you could put a breakpoint on that line, run the code again and do whos at the prompt when it stops on the error line.
I actually changed this function y = Eg(t) y = ilaplace(Egs(t),t,t);
with this function y = Eg(t) syms s; y = ilaplace(Egs(s),s,t); and it works…however I have other problems…I’ll put them in a different subject… sorry about the code…I’m new in here and thanks for your answers
I found a function here in mathworks called Erfi that i have to use it in a program. however, as I understood, this function doesn’t work for s as symbolic . however, i need to do ilaplace for a function that uses it… here is the error —————————— ??? Undefined function or method ‘gammainc’ for input arguments of type ‘sym’.
Error in ==> erfi1 at 19
ans=~isreal(t).*(-(sqrt(-t.^2)./(t+isreal(t))).*gammainc(-t.^2,1/2))+…
Error in ==> Epsf at 31
B5 =
D.^(7./4)*sqrt(pi)*dRH*(3*sqrt(D)-2*b*sqrt(s))*sqrt(-s./D)*(erfi1(sqrt(b)*(s./D).^(1./4))-erfi1(sqrt(r)*(s./D).^(1./4)))./(b.^(3./2)*s.^(9./4));
Error in ==> Egs at 25
y =
(1/k)*(a-b)*(a+b)*(Es/s)*D1*s*(b.^2*(nuc-1)-c.^2*(nuc+1))/(4*b.^2*(s*Epsf(s)-(s+lambda)*Epsf(s+lambda))+(b-c)*(b+c)*D1*((a.^2*(nus+1)-b.^2*(nus-1))));
Error in ==> Eg at 3
y = ilaplace(Egs(s),s,t);
Error in ==> graphe at 6
Ec = nu*Eg(t-tp);
————-
and here is the code
—————
k=1.7;
lambda=0.3;
tp=1;
nu = k*(1-exp(-lambda*tp));
t = 5:35;
Ec = nu*Eg(t-tp);
plot(t,Ec)
——————
function ans=erfi1(t)
xc=5.7;
it says that here is the error !
ans=~isreal(t).*(-(sqrt(-t.^2)./(t+isreal(t))).*gammainc(-t.^2,1/2))+…
isreal(t).*real(-sqrt(-1).*sign(t).*((t<xc).*gammainc(-t.^2,1/2))+…
(t>=xc).*exp(t.^2)./t/sqrt(pi));
————————
function y = Epsf(s)
a = 14;
b=15;
c=25;
L=c-b;
r=c;
phi=15;
V=7*7*28;
ro=1000;
RHi=100;
RHb=50;
dRH = RHb-RHi;
nus=0.3;
D=1;
M=8.3*10.^(-6);
k=1.7;
Es=200000;
nuc=0.2;
lambda=0.3;
tp=1;
nu = k*(1-exp(-lambda*tp));
B1 = b*sqrt(s)./sqrt(D);
B2 = c*sqrt(s)./sqrt(D);
B3 = r*sqrt(s)./sqrt(D);
B4 = -b*exp(B2)*(b-r)*(b+r)*RHi*sqrt(s)-3*c*exp(B2)*(b-r)*(b+r)*sqrt(s);
B5 = D.^(7./4)*sqrt(pi)*dRH*(3*sqrt(D)-2*b*sqrt(s))*sqrt(-s./D)*(erfi1(sqrt(b)*(s./D).^(1./4))-erfi1(sqrt(r)*(s./D).^(1./4)))./(b.^(3./2)*s.^(9./4));
RH= sqrt(D)*exp(-c*sqrt(s)./sqrt(D))*(-b*c*s./D).^(3./2)*((D).^(3./2)*sqrt(- b*c*s./D)*(-6*c.^(3./2)*(sqrt(6*D)*exp(B1)-exp(B3)*sqrt(D*r))*dRH- B4)./(b.^2*c.^2*s.^2)+B5)./(2*(3*c+b)*s.^(3./2));
y = -1.1*M*((c.^2-b.^2)*RHi./(2*s)-RH);
————————————————
function y = Egs(s)
a=14;
b=15;
c=25;
L=c-b;
r=c;
phi=15;
V=7*7*28;
ro=1000;
RHi=100;
RHb=50;
dRH = RHb-RHi;
nus=0.3;
D=1;
M=8.3*10.^(-6);
k=1.7;
Es=200000;
nuc=0.2;
lambda=0.3;
tp=1;
nu = k*(1-exp(-lambda*tp));
D1 = s*Epssa(s)-(s+lambda)*Epssa(s+lambda)/exp(lambda*tp);
y = (1/k)*(a-b)*(a+b)*(Es/s)*D1*s*(b.^2*(nuc-1)-c.^2*(nuc+1))/(4*b.^2*(s*Epsf(s)-(s+lambda)*Epsf(s+lambda))+(b-c)*(b+c)*D1*((a.^2*(nus+1)-b.^2*(nus-1))));
——————————————————
function y = Eg(t)
syms s;
y = ilaplace(Egs(s),s,t);
———————————
function ans = Epssa(s)
syms t;
ans = laplace(Epsa(t),t,s);
——————————-
function y = Epsa(t)
y = -16.7*10.^(-6)*t.^(0.3);
———————————
I really appreciate your help because I spent a lot of time in this issue
Вопрос:
Я получаю эту ошибку при запуске моего кода:
Ошибка при использовании == > mldivide Матричные измерения должны совпадать.
Вот мой код:
%make the plots of phase and group velocity vs discreteness of the grid
c=1;
a=input('Please enter the ratio cdt/dx : ')
figure(1)
R=2:40;
plot(R,phase_vel(R,a)/c)
xlabel('R=l/dx')
ylabel('u_phase/c')
%figure(2)
%plot(group_vel(R,a),R,0,40)
%xlabel('R=l/dx')
%ylabel('u_group/c')
и вот мои функции:
function phase_velocity = phase_vel(R,a)
%numerical phase velocity of the discrete wave
c=1;
phase_velocity=(2*pi*c)/(R*knum(R,a));
end
function group_velocity =group_vel(R,a )
%numerical group velocity of the discrete wave
c=1;
group_velocity=(a*sin(knum(R,a)))/(sin(2*pi*a/R))
end
function knumber = knum(R,a)
%This is the k wave number
knumber=acos((1/a)^2*(cos(2*pi*a/R)-1)+1);
end
Как я могу решить эту ошибку?
EDIT: Я использовал. оператора в каждом уравнении и я изменил пределы R = 4: 40
Лучший ответ:
Если ваша цель – применить ваши формулы к каждому отдельному значению в векторе R
, тогда вы должны выполнять все ваши вычисления, используя element-wise арифметические операторы .*
, ./
и .^
вместо матричных операторов *
, /
и ^
.
Ваша ошибка, вероятно, возникает при первом вызове вашей функции knum
, особенно при попытке вычислить 2*pi*a/R
. Поскольку 2*pi*a
является единственным скалярным значением, вы получаете ошибку при попытке выполнить матричное правое деление /
с помощью вектора строк R
, Самое странное – сообщение об ошибке:
??? Error using ==> mldivide
Matrix dimensions must agree.
что означает, что вы используете матричный оператор левого деления , которого вы явно не видите. Я тестировал это в MATLAB R2010b, и я получаю такое же неправильное имя функции, которое появляется в моем сообщении. Я думаю, что это может быть опечаткой в сообщении об ошибке, и я отложил записку для людей MATLAB, чтобы взглянуть на нее и очистить ее.
Ответ №1
У меня нет Symbolic Math Toolbox, но, похоже, ваша проблема заключается в том, что вы используете plot
, функцию, которая может обрабатывать массивы чисел и подавать результат в результате символического вычисления. Взгляните на справку Matlab, где Тема Создание сюжетов символических функций предлагает использовать ezplot()
. В качестве альтернативы вам нужно оценить свое символическое выражение для определенных входных значений, чтобы создать массив чисел, с которым может работать plot
, но вы не можете использовать double() для него, поскольку он не знал бы, какие числа подключаться к вашим переменным.
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.