Hi guys. I want to make some if conditional sentance.
I can't get a result, because of 'f'.
-----------------------------------------------------
f=[0:1:20]
f1=10;
E=20;
B0=15;
if (0<f && f<f1);
P = sqrt(E)/(2*B0);
elseif (f1<f && f<2*B0-f1);
P = (sqrt(E)/(4*B0))*(1+cos((pi*(abs(f)-f1))/(2*(B0-f1))));
else
P = 0
end
plot(f,2*B0*P/sqrt(E));
-----------------------------------------------------------------
Matlab says that && can't be used with doubled value..
Please help.

 Réponse acceptée

Stephen23
Stephen23 le 2 Avr 2015
Modifié(e) : Stephen23 le 2 Avr 2015

0 votes

Learn how to write vectorized code in MATLAB: vectorized code is faster, neater and less buggy. Firstly we define the parameters:
>> f = 0:20;
>> f1 = 10;
>> E = 20;
>> B0 = 15;
Then a vectorized solution can be achieved by directly using logical indexing:
>> P = (sqrt(E)/(4*B0)) * (1+cos((pi*(abs(f)-f1)) / (2*(B0-f1))));
>> P(0<f & f<f1) = sqrt(E)/(2*B0);
>> P(f==0 | f==f1) = 0;
>> P(:)
ans =
0
0.14907
0.14907
0.14907
0.14907
0.14907
0.14907
0.14907
0.14907
0.14907
0
0.14542
0.13484
0.11835
0.097568
0.074536
0.051503
0.030725
0.014235
0.003648
0

1 commentaire

baek
baek le 2 Avr 2015
It really helpful. Thanks. I never thought about like this.
Now I can make a really nice signal. Thank you

Connectez-vous pour commenter.

Plus de réponses (1)

James Tursa
James Tursa le 2 Avr 2015
Modifié(e) : James Tursa le 2 Avr 2015

0 votes

f is a vector, so the expression f<f1 is also a vector. And when you try to use this vector with the && operator you get the error message.
Either vectorize all of this to generate your P if you are up to the task, or wrap it in a loop to generate your P values using only one element of f in each iteration to generate one element of P.

1 commentaire

baek
baek le 2 Avr 2015
Yes. I thought it is quite difficult to solve. But there is a solution form 'Stephen Codeldick' under below. Thanks for your mention. :D

Connectez-vous pour commenter.

Catégories

En savoir plus sur MATLAB dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by