Does it have a statement for replacing repeated multiple if and elseif statements?

2 ビュー (過去 30 日間)
Jeah MK
Jeah MK 2022 年 2 月 28 日
回答済み: David Hill 2022 年 2 月 28 日
I have a code:
a = 0:0.001:1;
b = 0.03*sin(a);
for i = 1:length(a),
d = 0;
if b(i) <= 0.02;
if 0 < b(i) <= 0.1*pi/180
c = 0:0.1*pi/180:10*pi/180;
elseif 0.1*pi/180 < b(i) <= 0.2*pi/180
c = 0.1*pi/180:0.1*pi/180:10*pi/180;
elseif 0.2*pi/180 < b(i) <= 0.3*pi/180
c = 0.2*pi/180:0.1*pi/180:10*pi/180;
elseif 0.3*pi/180 < b(i) <= 0.4*pi/180
c = 0.3*pi/180:0.1*pi/180:10*pi/180;
elseif 0.4*pi/180 < b(i) <= 0.5*pi/180
c = 0.4*pi/180:0.1*pi/180:10*pi/180;
elseif 0.5*pi/180 < b(i) <= 0.6*pi/180
c = 0.5*pi/180:0.1*pi/180:10*pi/180;
elseif 0.6*pi/180 < b(i) <= 0.7*pi/180
c = 0.6*pi/180:0.1*pi/180:10*pi/180;
elseif 0.7*pi/180 < b(i) <= 0.8*pi/180
c = 0.7*pi/180:0.1*pi/180:10*pi/180;
elseif 0.8*pi/180 < b(i) <= 0.9*pi/180
c = 0.8*pi/180:0.1*pi/180:10*pi/180;
elseif 0.9*pi/180 < b(i) <= 1*pi/180
c = 0.9*pi/180:0.1*pi/180:10*pi/180;
end
end
for k = 1:length(c),
d = d + b(1,i)*c(1,k);
end
e(1,i) = d;
end
I wonder if there is any way to get the same result by replacing the repeated elseif statement.
Thank you!
  3 件のコメント
Jeah MK
Jeah MK 2022 年 2 月 28 日
@DGM sorry that the code is not clear. I modified it and the full code for my purpose. Thank you!
Cris LaPierre
Cris LaPierre 2022 年 2 月 28 日
Note that your conditional statements are not robust. Consider the following.
0 < 5 < 6
ans = logical
1
0 < -5 < 6
ans = logical
1
Both statements evaluate as true, though you likely intend for the 2nd one to be false. I would be more explicit with how I write these.
0 < -5 && -5 < 6
ans = logical
0

サインインしてコメントする。

採用された回答

David Hill
David Hill 2022 年 2 月 28 日
a = 0:0.001:1;
b = 0.03*sin(a);
interval=0:.1*pi/180:pi/180;
[~,~,idx]=histcounts(b,interval);
b=b(idx~=0);
for k=1:length(b)
e(k)=sum(b(k)*((idx(k)-1)*.1*pi/180:.1*pi/180:10*pi/180));
end

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 2 月 28 日
Use discretize() to determine the range of c values that you want to use.
Or... just take
round((b*180/pi),1)*pi/180
as the starting point for c.

カテゴリ

Help Center および File ExchangeNaming Conventions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by