Summing elements of any vector using a for loop?

조회 수: 19 (최근 30일)
Charlotte Davies
Charlotte Davies 2017년 4월 5일
답변: Image Analyst 2017년 4월 5일
How would I write code to sum all of the elements of any vector (ie a generic functions which can be applied to any vector) using a for loop? Here is what I have tried and I am stuck because there is an error in line 5 (for X).
My code:
function S = mySum(X)
%MYSUM Sum of elements
% S = MYSUM(X) is the sum of the elements of the vector
adder = 0
for X
adder = adder + X
end
S = adder + X

채택된 답변

Image Analyst
Image Analyst 2017년 4월 5일
No need for both adder and S. Simply have this:
function S = mySum(X)
% MYSUM Sum of elements
% S = mySum(X) is the sum of the elements of the vector or array X.
% Works for X of any number of dimensions and sizes.
S = 0;
for k = 1 : numel(X)
S = S + X(k);
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by