Writing a function that stops after three odd numbers have been found in a list.

2 次查看(过去 30 天)
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.

采纳的回答

Youssef  Khmou
Youssef Khmou 2013-9-7
try to enhance this version :
function Y=MyMod(X)
% List X
N=length(X);
Y=zeros(N,1); % solution
ctr=1; % Counter
for t=1:N
if mod(X(t),2)~=0
Y(ctr)=X(t);
ctr=ctr+1;
end
end
Y=Y(1:3); % First three
if sum(mod(X,2))==0
disp('0');
end

更多回答(2 个)

Image Analyst
Image Analyst 2013-9-7
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
Michael 2013-9-7
Thank you for the help reading through both of your functions helped me to understand how to attack this problem and create my own solution.

类别

Help CenterFile Exchange 中查找有关 App Building 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by