Write a function that checks whether an element occurs in a list.
20 次查看(过去 30 天)
显示 更早的评论
function Checking(x)
a=([1,3,5,8,9]);
if x==a
disp('It is an element')
else
disp('Not an element')
end
end
0 个评论
回答(3 个)
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
0 个评论
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
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 Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!