How to define a function with summation.

조회 수: 3 (최근 30일)
Mingxuan
Mingxuan 2022년 10월 22일
댓글: Walter Roberson 2022년 10월 22일
how would I define a function named ccsum , whose inputs are function handle f and the total number of terms for summation k. The output would be .
I got started on the code but got stuck
function s = ccsum(f,k);
s = sum(f(1,k));
end

채택된 답변

Walter Roberson
Walter Roberson 2022년 10월 22일
you cannot assume that the function handle refers to vectorized code, so you need to somehow invoke f on each of the integers 1 to k, and create a total.
The two fundamental ways of totalling values are:
  • if you have already calculated all of the values and stored them in an array then use sum()
  • if you have not already calculated the values, initialize the total to zero and then loop generating each of the terms in sequence, adding each value to the running total as you go.
  댓글 수: 1
Walter Roberson
Walter Roberson 2022년 10월 22일
You should not assume that the function returns a scalar by the way.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by