Pulling Even numbers from an array

13 ビュー (過去 30 日間)
Gina Barlage
Gina Barlage 2015 年 6 月 3 日
回答済み: Stephen23 2015 年 6 月 3 日
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
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
Stephen23 2015 年 6 月 3 日
Hers is a simple vectorized function:
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

カテゴリ

Help Center および File ExchangeIntroduction to Installation and Licensing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by