Using the find function to check if the numbers in an array are divisible by a given number
Show older comments
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?
Accepted Answer
More Answers (1)
Image Analyst
on 7 Jan 2023
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.
Categories
Find more on Linear Algebra in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!