Sum odd numbers in a matrix
Afficher commentaires plus anciens
Hello I'm a beginner and just going through some practice problems and I'm on one where I need to sum all the odd values in a matrix. Here's what I have so far.
It passes the first two of three tests, the first where x=[1], the second where x=[2 3 5 7 1 4], but failed when x=[2 3 5 7 1 4;9 1 5 8 3 2]. It failed test 2 when, on line 3, instead of putting length(x) I put x(end), and I'm not really sure why. Any help would be appreciated.
function y = oddsum(x)
v=[];
for i=1:length(x)
g=x(i)
if mod(g,2)==1
v(i)=x(i);
end
end
y = sum(v)
end
Réponses (1)
madhan ravi
le 10 Juin 2020
Modifié(e) : madhan ravi
le 10 Juin 2020
v = zeros(size(x)); % good habit is to preallocate
change length to numel that’s why people recommend to use numel() took a while to debug
Whole code can be written as
Wanted = sum(x(mod(x,2) == 1), 'all') % for versions < 2018b sum(sum(...))
Catégories
En savoir plus sur Tables dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!