Using the find function to check if the numbers in an array are divisible by a given number
이전 댓글 표시
x = 0:1:10
f = x.^2-x-1
M = find( ~mod(f,2) & ~mod(f,3))
I can use the ~mod(f,2) function to find if the numbers in an array are even but, when applying this to other numbers it returned 'M = 1×0 empty double row vector'. How would this also work when excluding values that are also divisible by another number. For example what numbers in the array are divisible by 3 and 5 but not by 7.
What is the general rule when approaching this?
채택된 답변
추가 답변 (1개)
Image Analyst
2023년 1월 7일
Try it this way:
x = 0 : 1 : 100;
f = x .^ 2 - x - 1;
% Determine factors so we can see which might work.
for k = 1 : length(f)
if f(k) < 0
continue
end
fprintf('Prime factors of %d are: ', f(k))
fprintf('%d ', factor(f(k)))
fprintf('\n');
end
% mod(f,11)
% mod(f,5)
% Find numbers divisible by both 5 and 11
indexes = find( mod(f, 5) == 0 & mod(f, 11) == 0)
numbers = f(indexes)
% Double check results to make sure they're integers:
numbers/5
numbers/11
% If the above are empty, then there is no pair satisfying the test.
카테고리
도움말 센터 및 File Exchange에서 Linear Algebra에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!