필터 지우기
필터 지우기

How to test for integers and delete integers that do not perform to the test

조회 수: 1 (최근 30일)
My assignment: Write a function sumDiv5 which receives one input argument and returns how many elements of the input variable are divisible by 5. You are not allowed to use FOR loops (we will study them next week)
My thinking is to divide the whole input by 5. Then to delete all the non-integer numbers (those not divisible by 5). How do I delete only the non-integer numbers instead of the whole matrix? (which is what my code does)
function output= sumDiv5 (input)
A=input/5;
if isreal(A) && rem(A,1)==0
else
A=[];
end
output=A;

채택된 답변

Image Analyst
Image Analyst 2015년 9월 27일
Close. Study this snippet and see what you can learn:
data = randi(100, 1, 30)
divBy5 = rem(data, 5)
By the way, don't use "input" as a variable name because it's the name of a built-in function.
  댓글 수: 4
Krish Desai
Krish Desai 2015년 9월 27일
편집: Stephen23 2015년 9월 27일
Ok, I'm displaying the correct for when I have a vector, but when I try to input a matrix:
sumDiv5([0 1 2 3 4; 2 5 8 13 15]),
I get
1 1 0 0 1
Do I have to completely change the code, or is there a simple fix?
Current code:
function output= sumDiv5 (numbers)
A= rem(numbers,5);
count=sum(A==0);
output=count;
Stephen23
Stephen23 2015년 9월 27일
편집: Stephen23 2015년 9월 27일
Try this:
function out = sumDiv5(mat)
out = sum(0==rem(mat(:),5));
end
And tested:
>> sumDiv5([0 1 2 3 4; 2 5 8 13 15])
ans = 3
Note that I also formatted the code in your question properly: in future please do this yourself by selecting the code text and clicking the {} Code button that you will find above the textbox.

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

추가 답변 (1개)

James Tursa
James Tursa 2015년 9월 27일
Hint: Take a look at the result of rem(A,1)==0. What do you get if you sum this up?

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by