can I apply a for loop inside the function so that I can make my program short?

1 view (last 30 days)
ti = 0;
tf = 10E-6;
tspan = [ti tf];
a = 0.6;
n = 0.05;
tc = 10E-9;
r = 1.5;
F = 10;
f = @(t,y) [
(-1/(2*tc)).*(1 - r/(1+ (y(1)^2)./F)).*y(1) + (n/(2*tc)).*((cos(y(6))).*y(2)) ;
(-1/(2*tc)).*(1 - r/(1+ (y(2)^2)./F)).*y(2) + (n/(2*tc)).*((cos(y(7))).*y(3) + (cos(y(6))).*y(1));
(-1/(2*tc)).*(1 - r/(1+ (y(3)^2)./F)).*y(3) + (n/(2*tc)).*((cos(y(8))).*y(4) + (cos(y(7))).*y(2));
(-1/(2*tc)).*(1 - r/(1+ (y(4)^2)./F)).*y(4) + (n/(2*tc)).*((cos(y(10))).*y(5) + (cos(y(8))).*y(8));
(-1/(2*tc)).*(1 - r/(1+ (y(5)^2)./F)).*y(5) + (n/(2*tc)).*((cos(y(9))).*y(4));
(a./(2*tc)).*( r/(1 + (y(2)^2)./F) - r/(1 + (y(1)^2)./F) ) + (n/(2*tc)).*(((y(3)./y(2)).*sin(y(7))) - (y(2)./y(1) + y(1)./y(2) ).*sin(y(6)) );
(a./(2*tc)).*( r/(1 + (y(3)^2)./F) - r/(1 + (y(2)^2)./F) ) + (n/(2*tc)).*(((y(4)./y(3)).*sin(y(8))) - (y(3)./y(2) + y(2)./y(3) ).*sin(y(7)) + (y(1)./y(2)).*sin(y(6)));
(a./(2*tc)).*( r/(1 + (y(4)^2)./F) - r/(1 + (y(3)^2)./F) ) + (n/(2*tc)).*(((y(5)./y(4)).*sin(y(8))) - (y(4)./y(3) + y(3)./y(4) ).*sin(y(8)) + (y(2)./y(3)).*sin(y(6)));
(a./(2*tc)).*( r/(1 + (y(5)^2)./F) - r/(1 + (y(4)^2)./F) ) + (n/(2*tc)).*(((y(3)./y(4)).*sin(y(8))) - (y(5)./y(4) + y(4)./y(5) ).*sin(y(9)));
(a./(2*tc)).*( - r/(1 + (y(5)^2)./F) ) + (n/(2*tc)).*((y(4)./y(5)).*sin(y(9)));
];
can I apply here the "for loop" inside where the function define. so the program will get short.
I wrote 10 equation in this, what if I want 20 equation ? can I apply for loop in this or any method.
[time,Y] = ode45(f,tspan,[1;1;1;1;1;1;1;1;1;1].*10E-6);
plot(time,Y(:,6))
hold on
plot(time,Y(:,7))
plot(time,Y(:,8))
plot(time,Y(:,9))
hold off
  4 Comments
per isakson
per isakson on 3 Aug 2022
Now I think I understand your question.
Are there typos in your anonymous function? This looks suspect. e.g. "y(8)" in three rows.
Does your anonymous function agree with the equations in your comment?

Sign in to comment.

Accepted Answer

Torsten
Torsten on 3 Aug 2022
Edited: Torsten on 3 Aug 2022
N = 5;
ti = 0;
tf = 10E-6;
tspan = [ti tf];
[time,Y] = ode45(@(t,y)f(t,y,N),tspan,[1;1;1;1;1;1;1;1;1;1].*10E-6);
function dy = f(t,y,N)
a = 0.6;
n = 0.05;
tc = 10E-9;
r = 1.5;
F = 10;
A = y(1:N);
phi = y(N+1:2*N);
dA = zeros(N,1);
dphi = zeros(N,1);
dA(1) = ...;
dphi(1) = ...;
for i = 2:N-1
dA(i) = ...;
dphi(i) = ...;
end
dA(N) = ...;
dphi(N) = ...;
dy = [dA;dphi];
end

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!