フィルターのクリア

Write a function that checks whether an element occurs in a list.

20 ビュー (過去 30 日間)
Yeap Jia Wei
Yeap Jia Wei 2015 年 6 月 11 日
回答済み: Walter Roberson 2021 年 8 月 1 日
function Checking(x)
a=([1,3,5,8,9]);
if x==a
disp('It is an element')
else
disp('Not an element')
end
end

回答 (3 件)

Stephen23
Stephen23 2015 年 6 月 12 日
編集済み: Stephen23 2015 年 6 月 12 日
Actually your code just needs the addition of any to work correctly:
function Checking(x)
a = [1,3,5,8,9];
if any(x==a)
disp('It is an element')
else
disp('Not an element')
end
end
and here it is being tested:
>> Checking(2)
Not an element
>> Checking(3)
It is an element
Read the if documentation carefully to know why this works!

Walter Roberson
Walter Roberson 2021 年 8 月 1 日
function Checking(x)
if ismember(x, [1,3,5,8,9])
disp('It is an element')
else
disp('Not an element')
end
end

Sreeja Banerjee
Sreeja Banerjee 2015 年 6 月 12 日
Hi Yeap,
Assuming that x is the element you want to check and a is the array, this function will not because you are comparing a 1x1 double with a 1xn double array. You need to compare each element of a with that of x.
Please look at the following code where I have used a FOR loop:
function Checking(x)
a=([1,3,5,8,9]);
for i = 1:length(a)
if x==a(i)
disp('It is an element')
else
disp('Not an element')
end
end
  1 件のコメント
Walter Roberson
Walter Roberson 2015 年 6 月 12 日
Note that will say it is Not an element once for each element of "a" that it does not equal.

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by