# Summing the even index elements of a 1D array

3 Ansichten (letzte 30 Tage)
Camden Nelson am 6 Mai 2023
Kommentiert: Camden Nelson am 6 Mai 2023
I am trying to write a recursive function that sums the elements in even indexed position of a 1D array, but am not sure how to do this. I have some of the code started below, but it is obvously incorrect:
function [out] = mySumEven(A)
n = length(A);
if n == 1
out = 'No numbers in even positions';
elseif n == 2
out = A(2);
else
out = A(2) + mySumEven(A(4:n));
end
end
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Atsushi Ueno am 6 Mai 2023
Bearbeitet: Atsushi Ueno am 6 Mai 2023
mySumEven([1 2 3 4 5 6 7 8 9])
No numbers in even positions
ans = 20
function [out] = mySumEven(A)
n = length(A);
if n == 1
disp('No numbers in even positions'); % out = 'No numbers in even positions';
elseif n == 2
out = A(2);
else
out = A(2) + mySumEven(A(3:n)); % out = A(2) + mySumEven(A(4:n));
end
end
##### 2 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
Camden Nelson am 6 Mai 2023
That makes a lot of sense. Explains why I was getting some bizarre answers. Thank you so much!

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

R2023a

### Community Treasure Hunt

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

Start Hunting!

Translated by