How do I make a function that checks the divisibility of a given number, n, by 3, 5, 7, and 11.

I am trying to write a function div - divisibility(n) that checks the divisibility of a given number input n, by 3, 5, 7, and 11 for a hw problem. The problem requires that my output be a logical vector output of 4 elements corresponding to the divisibility by 3, 5, 7 and 11, respectively. For example, the output of divisibility(14) would be [0 0 1 0]. I have figured out how to write a function that gives a single output, but I do not know how to write a function that outputs a logical vector.
All I have so far is:
function div = divisibility(a)
div = rem(a,3)
end

 채택된 답변

This works:
divisibility = @(x) rem(x, [3 5 7 11]) == 0;
div = divisibility(14)
producing:
div =
0 0 1 0

댓글 수: 4

My pleasure!
That was actually a fun problem!
When you run the function like this, you produce both the div logical array and an ans logical array. How do you get rid of the ans logical array
the posted code does not produce ans

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

22 is divisible by 11. The logical command makes all nonzeros into ones and the tilde (~) then takes the not of the logical. What you're left with is a one wherever the remainder is zero.
a = 22;
div = ~logical(rem(a,[3 5 9 11 44]))

카테고리

도움말 센터File Exchange에서 Entering Commands에 대해 자세히 알아보기

질문:

2015년 4월 30일

댓글:

2021년 10월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by