Effacer les filtres
Effacer les filtres

What is wrong with my code in writing a for loop function

2 vues (au cours des 30 derniers jours)
Coupe Honda
Coupe Honda le 12 Fév 2017
Modifié(e) : Jan le 12 Fév 2017
function mysums(v)
sum_even=0;
sum_odd=0;
i=1;
for k = v
if mod(i,2)==0 & i<= size(v)
sum_even = sum_even + i;
else if i <= size(v)
sum_odd = sum_odd + i;
end
i = i+1;
end
disp([sum_odd , sum_even])
end
The loop is to sum odd nums and even nums from a vector input

Réponse acceptée

Jan
Jan le 12 Fév 2017
Modifié(e) : Jan le 12 Fév 2017
size(v) replies a vector, such that i <= size(v) will not do, what you expect.
USe the automatic code indentation to find the problem of using "else if" instead of "elseif" immediately.
Prefer to write a loop like:
for i = 1:numel(v)
if mod(i, 2) == 1
...
else
...
Use v(i) to get the current element, not sum_odd = sum_odd + i, because you do not want to collect the indices - when I assume that your other question contains the text of this homework.

Plus de réponses (0)

Catégories

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

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by