Pulling Even numbers from an array

18 visualizzazioni (ultimi 30 giorni)
Gina Barlage
Gina Barlage il 3 Giu 2015
Risposto: Stephen23 il 3 Giu 2015
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.

Risposte (2)

Image Analyst
Image Analyst il 3 Giu 2015
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 il 3 Giu 2015
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

Categorie

Scopri di più su Introduction to Installation and Licensing in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by