is the "for loop" is wrong? what can be the solution?
Ältere Kommentare anzeigen
clc
ti = 0;
tf = 100E-4;
tspan=[ti tf];
o = 1E6;
tc = 70E-9;
tf = 240E-6;
a1 = 0.02;
a2 = 0.02;
P1 = 1;
P2 = 1;
k = 0.033;
l = 0.5;
f = @(t,y) [ ((y(2)-a1).*y(1)) + k.*(y(1).*cos(y(3))).*(2/tc);
(P1 - y(2).*(1+y(1)))./tf;
o - (k / tc) * 2 * sin(y(3));
];
[T,Y] = ode45(f,tspan,[1;1;0].*10E-3);
% this is the for loop, maybe this is wrong
Y(:,3) = -3:0.01:3;
U = zeros(length(k),1) ;
for i = 1:length(k)
U(i) = -o.*(Y(:,3)) - 2.*(k./tc).*cos(Y(:,3) - pi/2)
end
%plotting the graphs
plot(T,Y(:,3));
xlim([0 10E-5])
xlabel('t')
ylabel('phase difference')
legend('k = 0.033')
plot(Y(:,3),U)
6 Kommentare
Abderrahim. B
am 20 Jul. 2022
Hi!
The below lines of code are not correct. Read the comments below and try to rereview your code, and maybe you share what you are trying to do with this for loop.
Y(:,3) = -3:0.01:3; % this assignement is not correct size(-3:0.01:3) is different from size(Y(:,3))
U = zeros(length(k),1) ; % k is a scalar thus U is a scalar
for i = 1:length(k) % length(k) is one >> one iteratio, what is the point to use a for loop!!
U(i) = -o.*(Y(:,3)) - 2.*(k./tc).*cos(Y(:,3) - pi/2) % This assignment is not possible size(U(i)) does not match the size of the right side.
end
SAHIL SAHOO
am 20 Jul. 2022
Abderrahim. B
am 20 Jul. 2022
Okay now is clear what you re trying to do. You do not need a loop. One of MATLAB advantages is vectorization. Check out @Torsten answer.
VBBV
am 20 Jul. 2022
You can also use for loop as shown in your code. But plot you mentioned plot (Y(:,3), Φ) is strange. It will be a straight line since Y(:,3) and Φ are same according to your equation and code written. Do you mean plot (Y(:,3), U) ?
VBBV
am 20 Jul. 2022
The for loop code works well as shown in my answer below. which can also be done without a loop.
SAHIL SAHOO
am 20 Jul. 2022
Akzeptierte Antwort
Weitere Antworten (1)
ti = 0;
tf = 100E-4;
tspan=[ti tf];
o = 1E6;
tc = 70E-9;
tf = 240E-6;
a1 = 0.02;
a2 = 0.02;
P1 = 1;
P2 = 1;
k = 0.033;
l = 0.5;
f = @(t,y) [ ((y(2)-a1).*y(1)) + k.*(y(1).*cos(y(3))).*(2/tc);
(P1 - y(2).*(1+y(1)))./tf;
o - (k / tc) * 2 * sin(y(3));
];
[T,Y] = ode45(f,tspan,[1;1;0].*10E-3);
% this is the for loop, maybe this is wrong
U = -o.*Y(:,3) - 2.*(k./tc).*cos(Y(:,3) - pi/2);
%plotting the graphs
plot(T,Y(:,3));
xlim([0 10E-5])
xlabel('t')
ylabel('phase difference')
legend('k = 0.033')
plot(Y(:,3),U)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!






