I am getting an error as "Operands to the || and && operators must be convertible to logical scalar values. Error in xd (line 8) if (t>=t1)&&(t<t2)".

1 回表示 (過去 30 日間)
my code is
t1 = 0;
t2 = 10;
t3 = 20;
t4 = 30;
t = 0:50;
if (t>=t1)&&(t<t2)
r = 0.6;
if (t>=t2)&&(t<t3)
r = 0.3;
if (t>=t3)&&(t<t4)
r = 0.3;
if (t>=t4)
r = 0.6;
end
end
end
end
plot(t,r)

採用された回答

Omer Yasin Birey
Omer Yasin Birey 2019 年 1 月 17 日
編集済み: Omer Yasin Birey 2019 年 1 月 17 日
You cannot compare a vector t (which is 1x51 double) with a single value for an if statement, with the logical operators. Even if you could, the plot at the end won't give anything. I believe you want to do this.
t1 = 0;
t2 = 10;
t3 = 20;
t4 = 30;
t = 0:50;
r = zeros(length(t),1);
for i = 1:length(t)
if (t(i)>=t1)&&(t(i)<t2)
r(i) = 0.6;
elseif (t(i)>=t2)&&(t(i)<t3)
r(i) = 0.3;
elseif (t(i)>=t3)&&(t(i)<t4)
r(i) = 0.3;
else
r(i) = 0.6;
end
end
plot(t,r)
axis([0 60 0.2 0.7])
  2 件のコメント
Stephen23
Stephen23 2019 年 1 月 17 日
編集済み: Stephen23 2019 年 1 月 17 日
"You cannot compare a vector t (which is 1x51 double) with a single value for an if statement"
Actually you can: comparing a vector against a scalar value is permitted, and providing a non-scalar condition to if is also permitted (but you should read the if documentation very carefully before using this):
>> if [1,2,3]>0, disp('oh, it works!'), end
oh, it works!
>>
Personally I would recommend against non-scalar if or while conditions, but they certainly are possible in MATLAB.
Omer Yasin Birey
Omer Yasin Birey 2019 年 1 月 17 日
Yes Stephen, you are right. I edited this.

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

その他の回答 (2 件)

Stephen23
Stephen23 2019 年 1 月 17 日
編集済み: Stephen23 2019 年 1 月 17 日
Learn to use logical indexing
Logical indexing is a very basic MATLAB concept that will make your code simpler and more efficient:
>> t1 = 0;
>> t2 = 10;
>> t3 = 20;
>> t4 = 30;
>> t = 0:50;
>> r = nan(size(t));
>> r((t>=t1)&(t<t2)) = 0.6;
>> r((t>=t2)&(t<t3)) = 0.3;
>> r((t>=t3)&(t<t4)) = 0.3;
>> r((t>=t4)) = 0.6;
>> plot(t,r)

madhan ravi
madhan ravi 2019 年 1 月 17 日
編集済み: madhan ravi 2019 年 1 月 17 日
&& and || for scalars for vectors use & and | , logical indexing is efficient:
t1 = 0;
t2 = 10;
t3 = 20;
t4 = 30;
t = 0:50;
r = zeros(size(t));
id1=(t>=t1)&(t<t2)|(t>=t4);
r(id1)=0.6
id2=(t>=t2)&(t<t3);
r(id2) = 0.3;
id3=(t>=t3)&(t<t4)
r(id3) = 0.3;
plot(t,r)
axis([0 60 0 1])

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by