write a matlab function evennumbersx that given a vector of
write a matlab function even_numbers(x) that given a vector of natural numbers returns a vector that only contains the even numbers. example:
>>even_numbers([2 3 4 1 2222 2])
ans= [2 4 4 2222 2]
can you do this without manually looping over the input vector? ( you can add an element z to an existing vector y using y=[y z]; if you need it.)
Solution
% Save this function with same file name (even_numbers) and in command window type the
% function even_numbers(x) where x is the input
% Example: even_numbers1([1 2 3 4])
% ans = 2 4
function [y] = even_numbers(x)
num = length(x); % Length of the array
temp = rem(x,2); % Remainder when divided by 2
j = 1;
for i = 1:num
if temp(i)==0 % If remainder is zero store in y
y(j) = x(i); % output even vector
j = j+1;
end
end
end
Without Manually Looping over the input
function [y] = even_number(x)
temp = rem(x,2); % Remainder when divided by 2
loc = find(temp==0); % Find the location when remainder is zero
y = x(loc); % create the output vector finding values from x where temp is zero
end
