Write a function that checks whether an element occurs in a list.
조회 수: 18 (최근 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!