Pulling Even numbers from an array
이전 댓글 표시
My assignment was to create a function where it had to count the number of even numbers in the array given and display the count if there were even numbers. This is what I have so far....
function [] = script28_gina_barlage(M)
sum_total = 0;
string1 = ['There are ' num2str(sum_total) ' even numbers.'];
%
for ii = M
if mod(ii,1)==2 & any(ii== M)
sum_total = sum_total + 1;
disp(string1)
else
sum_total = sum_total;
disp('There are no even numbers.')
end
end
I am not sure how to pull out the even numbers. Right now it just repeats 'There are no even numbers.' however many numbers are in the array times.
답변 (2개)
Image Analyst
2015년 6월 3일
Close, but you need to mod with 2, not 1, and don't display the total until you're done with the loop:
M = randi(9, 1, 20)
sum_total = 0;
for ii = M
if mod(ii, 2)== 0
sum_total = sum_total + 1;
fprintf('%d is even.\n', ii);
end
end
message = sprintf('There are %d even numbers.', sum_total);
uiwait(helpdlg(message));
Stephen23
2015년 6월 3일
function [] = script28_gina_barlage(M)
X = nnz(mod(M(:),2)==0);
if X==0
fprintf('There are no even numbers\n')
else
fprintf('There are %d even numbers\n',X)
end
and tested:
>> script28_gina_barlage([1,2,3,4,5])
There are 2 even numbers
>> script28_gina_barlage(1:2:11)
There are no even numbers
>> script28_gina_barlage(2*ones(4))
There are 16 even numbers
카테고리
도움말 센터 및 File Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!