Pulling Even numbers from an array
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (2)
Image Analyst
am 3 Jun. 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));
0 Kommentare
Stephen23
am 3 Jun. 2015
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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Introduction to Installation and Licensing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!