double for loop errors

21 Ansichten (letzte 30 Tage)
fatmah hasan
fatmah hasan am 13 Mär. 2022
Bearbeitet: Walter Roberson am 13 Mär. 2022
%part 8
m=1.24;
td=10;
P0=1;
w_n=0:50/80:50;
t=0:30/80:30;
for ii=1:length(t);
jj=1:length(w_n);
Tn(jj)=(2*pi)./(w_n(jj));
%tt(ii)=(td/Tn(ii));
if 0<t(ii)<td/2;
xt(ii)=2*(t(ii)/td)-2*(Tn(jj)/2*pi*td)*sin(t(ii)/Tn(jj));
elseif td/2<t(ii)<td;
xt(ii)=2*(1-(t(ii)/td)+(Tn(jj)/2*pi*td)*(2*sin((2*pi/Tn(jj)*(t(ii)-0.5*td)))-sin(2*pi*t(ii)/Tn(jj))));
elseif t(ii)>td;
xt(ii)=2*((Tn(jj)/2*pi*td)*(2*sin((2*pi/Tn(jj)))*(t(ii)-td))-sin((2*pi/Tn(jj))*(t(ii)-td))-sin(2*pi*t(ii)/Tn(jj)));
end
end
Error using /
Matrix dimensions must agree.
tt=(td./Tn);
M=max(xt(jj));
%derivative
figure(1)
plot(tt,M)
I am trying to get the maximum values for different values of w_n but it either the figure that's incorrect or problem wih the double for loop

Antworten (1)

Walter Roberson
Walter Roberson am 13 Mär. 2022
Bearbeitet: Walter Roberson am 13 Mär. 2022
%part 8
m=1.24;
td=10;
P0=1;
w_n=0:50/80:50;
t=0:30/80:30;
for ii=1:length(t);
jj=1:length(w_n);
Tn(jj)=(2*pi)./(w_n(jj));
%tt(ii)=(td/Tn(ii));
if 0<t(ii) & t(ii)<td/2;
xt(ii)=2*(t(ii)/td)-2*(Tn(jj)/2*pi*td)*sin(t(ii)/Tn(jj));
elseif td/2<t(ii) & t(ii)<td;
xt(ii)=2*(1-(t(ii)/td)+(Tn(jj)/2*pi*td)*(2*sin((2*pi/Tn(jj)*(t(ii)-0.5*td)))-sin(2*pi*t(ii)/Tn(jj))));
elseif t(ii)>td;
xt(ii)=2*((Tn(jj)/2*pi*td)*(2*sin((2*pi/Tn(jj)))*(t(ii)-td))-sin((2*pi/Tn(jj))*(t(ii)-td))-sin(2*pi*t(ii)/Tn(jj)));
elseif t(ii) == 0
xt(ii) = nan;
else
fprintf('td is %.16g, t(ii) is %.16g\n', td, t(ii));
error('missed a t case')
end
end
Error using /
Matrix dimensions must agree.
tt=(td./Tn);
M=max(xt(jj));
%derivative
figure(1)
plot(tt,M)
That error is because you are calculating xt(ii) [which is a single value] in terms of the vector Tn(jj)
You have not coded a double for loop. You have a single for loop, and inside that for loop you start with a vector assignment statement. If you want a double for loop, you have to use the keyword for each time.
for ii = 1 : length(t)
for jj = 1 : length(w_n)
and remember that in statements such as
xt(ii)=2*(t(ii)/td)-2*(Tn(jj)/2*pi*td)*sin(t(ii)/Tn(jj))
that if ii is scalar, you are overwriting **all* of xt(ii) for each different jj value.
You either need to output 2 dimensional arrays, or else you need something that "summarizes" the calculations over the jj range, such as a sum() statement, or else as you work through each jj entry you need to add (or subtract or multiply or whatever) to modify the current xt(ii) value, such as
xt(ii) = xt(ii) + 2*(t(ii)/td)-2*(Tn(jj)/2*pi*td)*sin(t(ii)/Tn(jj))

Kategorien

Mehr zu Graphics Performance finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by