sum by recursion without using sum of Matlab
이전 댓글 표시
Question: "Write a function with header [S] = mySum(A) where A is a one-dimensional array, and S is the sum of all the elements of A. You can use recursion or iteration to solve the problem, but do not use MATLAB’s function sum." Answer (there is error)
function [S] = mySum(A)
% this program is the sum of all the elements of A
%A is a one dimention array
%get A
[n]=size(A);
if n==1
% base case.
S= A(1);
elseif n==2
%base case
S=A(1) + A(2);
else
%recusrive step
S = mySum(A(n-1)) + mySum(A(n-2));
end
end
Where is the error?
댓글 수: 2
Steven Lord
2016년 9월 3일
The size function, with one output, returns a vector with ndims(A) elements. When you use if (or elseif) with a nonempty vector in the condition, the body of the if or elseif statement is only executed if ALL the elements of the vector are nonzero.
Tho Gonzalez
2016년 9월 4일
채택된 답변
추가 답변 (1개)
I will give my input for this problem. Me like others who searched on this problem might wanna get an easy overlook of the answer.
My assignment was to write a function which sums all the elements in a vector, with recursion. I want to add that I'm a beginner so don't put too much faith in my coding.
This is how I solved it:
function S = mySum(A)
n = 1:length(A);
if n == 1 % Base case
S = A(1);
else
Last_term = A(end);
Term_before_last_term = mySum(A(1:end-1)); % Recursive step
S = Last_term + Term_before_last_term;
end
end
If someone with greater knowledge than me would be inclined to criticize this, I gladly hear it.
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!