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

6 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Youssef  Khmou
Youssef Khmou am 7 Sep. 2013
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

Weitere Antworten (2)

Image Analyst
Image Analyst am 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
Michael am 7 Sep. 2013
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.

Kategorien

Mehr zu App Building finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by