Summing the even index elements of a 1D array

4 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Atsushi Ueno
Atsushi Ueno il 6 Mag 2023
Modificato: Atsushi Ueno il 6 Mag 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';
out = 0; % added
elseif n == 2
out = A(2);
else
out = A(2) + mySumEven(A(3:n)); % out = A(2) + mySumEven(A(4:n));
end
end
  2 Commenti
Atsushi Ueno
Atsushi Ueno il 6 Mag 2023
MATLAB can add numerical values and character vectors. The output is as numeric vector. It means every charactor code have been added by 1.
1 + [1 2 3 4]
ans = 1×4
2 3 4 5
1 + 'No numbers in even positions'
ans = 1×28
79 112 33 111 118 110 99 102 115 116 33 106 111 33 102 119 102 111 33 113 112 116 106 117 106 112 111 116
char(ans)
ans = 'Op!ovncfst!jo!fwfo!qptjujpot'
Camden Nelson
Camden Nelson il 6 Mag 2023
That makes a lot of sense. Explains why I was getting some bizarre answers. Thank you so much!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Prodotti


Release

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by