In an assignment A(I) = B, the number of elements in B and I must be the same.
古いコメントを表示
Good day,
I am trying to numerically solve two differential equations and run into the error "In an assignment A(I) = B, the number of elements in B and I must be the same." at d_dt(2)=2*w.*r.*thetap+((w^2)+(thetap.^2)).*r;
Script:
R=1000000;
w=0.0031413613; %0.18 degrees in radians
Tr=2000;
Ac=(w^2)*R;
vp=w*R;
m=1;
d=0.1;
c1=(0.00155)*d;
[t,xmat]=ode45(@funcfin, [0 300], [0 vp 0 0]);
h=R-xmat(:,1);
figure(1)
plot(h,xmat(:,3))
xlabel('height')
ylabel('phi')
title('height vs phi')
Function file:
function d_dt=funcfin(t,g)
global w
r=g(1);
rp=g(2);
theta=g(3);
thetap=g(4);
d_dt=zeros(4,1);
d_dt(1)=rp;
d_dt(2)=2*w.*r.*thetap+((w^2)+(thetap.^2)).*r;
d_dt(3)=thetap;
d_dt(4)=((-2.*rp)./r).*(w+thetap);
Thank you for your time.
採用された回答
その他の回答 (1 件)
Brendan Hamm
2015 年 4 月 30 日
編集済み: Brendan Hamm
2015 年 4 月 30 日
It appears in this code that all of the values on the RHS are scalars, so this should not be an issue. That being said something is obviously happening, so you should use the debugging tools in MATLAB to diagnose this. In particular set a breakpoint at the line that causes the error and execute the code again. This will allow you to look into the workspace of the function and see if any of the variables in the line are not scalar values (possibly complex values which are stored as a 2 element vector).
Other thoughts on this code:
1. Why do you use .* if you expect these variables (r,*w*,*thetap*) to be scalars instead of just using *?
2. Why use a global variable?
In general it is not recommended to use global variables if you can avoid them. Here is how you avoid it here:
function d_dt = funcfin(t,g,w)
r=g(1);
rp=g(2);
theta=g(3);
thetap=g(4);
d_dt= [ rp; 2*w.*r.*thetap+((w^2)+(thetap.^2)).*r; thetap; ((-2.*rp)./r).*(w+thetap)];
end
Now your function knows about w, but many "function-functions" like ode solvers cannot deal with these extra inputs. For this reason we have anonymous functions:
w = toRadians('degrees',0.18); % Get the full precision of a double value
myFuncFin = @(t,g) funcfin(t,g,w);
This will behave exactly like your previous function, except there is no need to have a global variable, we can embed the value of w directly into the function's workspace. Now you can pass this function to the ode solver:
[t,xmat] = ode45(@myFuncFin, [0 300], [0 vp 0 0]);
Global variables can make debugging very difficult, so I recommend changing your code to the above before attempting the debugger.
Good Luck!
カテゴリ
ヘルプ センター および File Exchange で Ordinary Differential Equations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!