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

조회 수: 6 (최근 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