Summing the even index elements of a 1D array
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Atsushi Ueno
2023-5-6
编辑:Atsushi Ueno
2023-5-6
mySumEven([1 2 3 4 5 6 7 8 9])
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 个评论
Atsushi Ueno
2023-5-6
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]
1 + 'No numbers in even positions'
char(ans)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!