How do I make my for-loop control the signs (+/-) of two variables ("x1hat" and "x2hat") for each loop?

4 次查看(过去 30 天)
Depending on the signs of "x1hat" and "x2hat" i want the for-loop to calculate "W" differently. If "x1hat" and "x2hat" are of the same sign I want to calculate "W" in one way and if they are of different signs I want to calcutate "W" in another way. I tried my best to complete this with an "If-else-statement", but it doesnt look right in the plot..
Please help me with suggestion on how to improve the code. (asuming that all other variables are correctly defined)
[x1hat,x2hat]=deal(zeros(length(fv),1));
for n=1:length(fv)
f=(fv(n))
I=(Ihat(n))
Fhat=I*BL
A=[(-((2*pi*f)^2))*M+K]
fhat=[Fhat;0]
xhat=A\fhat
x1hat(n)=xhat(1)
x2hat(n)=xhat(2)
if((x1hat(n)>=0 & x2hat(n)>=0)|(x1hat(n)<0 & x2hat(n)<0))
W=(((2*p*pi^3)/c)*(f^4))*((abs(S1*x1hat(n))-abs(S2*x2hat(n)))^2)
else
W=(((2*p*pi^3)/c)*(f^4))*((abs(S1*x1hat(n))+abs(S2*x2hat(n)))^2)
end
W2=(((2*p*pi^3)/c)*(S1^2)*((Fhat^2)/(mA1+mspool)^2)*((f^4)/((((2*pi*f0)^2)-((2*pi*f)^2))^2)))
plot(f,W,f,W2,'r*')
xlabel('frequecie')
ylabel('sound power')
hold on;
end

回答(1 个)

Jan
Jan 2021-1-22
编辑:Jan 2021-1-22
A simplification:
if (x1hat(n) >= 0) == (x2hat(n) >= 0)
...
else
...
end
Avoid unnneded square brackets or parentheses.
Move repeated code outside the loop.
x1hat = zeros(length(fv), 1);
x2hat = zeros(length(fv), 1);
AxesH = axes('nextplot', 'on');
xlabel('frequecie')
ylabel('sound power')
for n = 1:length(fv)
f = fv(n);
I = Ihat(n);
Fhat = I * BL;
A = -((2 * pi * f)^2) * M + K;
fhat = [Fhat; 0];
xhat = A \ fhat;
x1hat(n) = xhat(1);
x2hat(n) = xhat(2);
if (x1hat(n) >= 0) == (x2hat(n) >= 0)
m = -1;
else
m = 1;
end
W = (2 * p * pi^3/c) * f^4 * (abs(S1 * x1hat(n)) + m * abs(S2 * x2hat(n)))^2;
W2 = (2 * p * pi^3/c) * (S1^2) * ((Fhat^2) / (mA1 + mspool)^2) * ...
(f^4 / (((2*pi*f0)^2 - (2*pi*f)^2)^2));
plot(AxesH, f, W, f, W2, 'r*');
end

Community Treasure Hunt

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

Start Hunting!

Translated by