How can I get inner matrix dimensions to agree for this loop?

3 次查看(过去 30 天)
Hello, I'm attempting to set up an Euler method to solve a SOLDE involving an RLC circuit. I'm encountering an error during the loop iteration where I set up values of current (I) to be reiterated. Despite using .* I can't seem to resolve the matrix error.
% The second order differential equation can be split into two first orders
% creating a system of equations to evaluate:
% -- dQ/dt=I --
% -- dI/dt=(-R/L)I-(1/LC)Q+(eo/L)cos(wdt) --
% Parameters Defined
L=2.5; %milli-Henries
C=70; %micro-Farads
R=1.5; %Ohms
epsilon=1.5; %milli-Volts
% coefficients
a=1;
b=R/L;
c=1/(L*C);
% Equation Variables Defined further + time interval
wR=sqrt(c/a);
t0=0; dt=0.1;
te=10*((2*pi)/wR);
t=(t0:dt:te);
n=(te-t0)/dt;
delw=R/L;
wd=[wR-delw,wR+delw];
% Method
Q=zeros(size(t)); % preallocating spaces
I=zeros(length(t));
Q(1)=0;
I(1)=0;
for i=1:n
t(i+1)=t(i)+dt;
Q(i+1)=Q(i)+dt*(I(i));
I(i+1)=I(i)+dt*((-R/L).*I-(1/L*C).*Q(i)+(epsilon/L)*cos(wd.*t));
end
plot(t,Q)
So the method is to make two first order differentials from the one second order differential, but I'm not sure why this error is occuring. Do I need to reevaluate the expression for I(i+1)? Should I define preallocated spaces differently?

回答(1 个)

Walter Roberson
Walter Roberson 2019-10-2
I=zeros(length(t));
That creates a matrix which is length(t) by length(t) . However, you only ever index I with a single subscript, as if you believe that I is a vector instead of 2D.
When you use zeros() with a single input that is a scalar, then it creates a square matrix of that order.
  2 个评论
Sean Rapp
Sean Rapp 2019-10-3
Hi Walter,
I don't comprehend the implications of the index / subscript. Is the problem arising because t is denoted through
t=(t0:dt:te);
which is a long row vector and I is denoted through a matrix?
Walter Roberson
Walter Roberson 2019-10-3
No. You make I into 8132 by 8132. Your sub expression for I(i+1) uses unindexed I as the right hand side of the .* operation, so the calculation up to there becomes 8132 by 8132. The cos(t) in the last sub expression is 1 x 8132. So you are adding an 8132 x 8132 and 1 x 8132. That is an error before R2016b. As of R2016b it became legal and will give an 8132 x 8132 answer. You then try to store the large square matrix at the single location I(i+1)
Whenever you are storing to a scalar location then all of the sub expressions need to produce scalars. You should be examining all of the variables and asking whether they need to be subscripted. Unless you are using them within sum() or prod() or any() or all() or in some limited cases / or \ then chances are that you should be subscripting to work with a single entry.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by