Effacer les filtres
Effacer les filtres

Having trouble with functions

1 vue (au cours des 30 derniers jours)
Matthew Benjamin
Matthew Benjamin le 10 Fév 2014
Commenté : Matthew le 10 Fév 2014
So I have this problem for school and I don't know how to take an element out of an array or matrix and put it into another one. Here is the question:
Create a function meancomp that compares the mean value of the odd numbered elements with the mean value of the even numbered elements and returns:
0, if they are equal
1, if the mean of the odd numbered elements is greater,
2, if the mean of the even numbered elements is greater"
This is what I have:
for m=1:length(x)
if mod(x,2)==0 % code end

Réponse acceptée

Image Analyst
Image Analyst le 10 Fév 2014
No. Just extract them like this
oddElements = A(1:2:end);
same for even but you start at 2 instead of 1, though you can still end at "end". To find the mean of an array, use mean
oddMean = mean(oddElements);
I trust you can take it from there because you know how if/else statements work.
  1 commentaire
Matthew
Matthew le 10 Fév 2014
This was extremley helpful, thank you.
My problem now is making the if/else statements into one function called meancomp. This is what I have and it only displays '2'.
function p=meancomp(A)
oddElements=A(1:2:end);
evenElements=A(2:2:end);
oddMean=mean(oddElements);
evenMean=mean(evenElements);
if evenMean==oddMean
disp('0');
elseif evenMean<oddMean
disp('1');
else
disp('2');
end
end

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by