Writing a function that stops after three odd numbers have been found in a list.
Show older comments
I'm trying to write a script that will find the first three odd numbers in a list if there aren't three it should display "0". My current script determines if a single number is wrong but it doesn't go further than that.
function [ r ] = MyMod( x,y )
while x >= 0
x=x-y;
end
r=x+y;
if r>0 disp('odd')
end
end
Thanks for any help in advance.
Accepted Answer
More Answers (2)
Image Analyst
on 7 Sep 2013
I presume the implied question here is "How do I do it?" Here's one way:
% Create sample data
% Uncomment one of these
% m = [2 4 5 6 7 9 2 1 0] % Case with >3 odd #'s
m = [2 2 4 3 5 2] % Case where 0 should be displayed
% Now, find the first 3 odd values, displaying 0 if there are less than 3.
oddIndexes = find(mod(m, 2))
if length(oddIndexes) >= 3
out = m(oddIndexes(1:3))
else
out = 0
end
Michael
on 7 Sep 2013
0 votes
Categories
Find more on App Building in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!