Creating a general function handle

  • Thread starter Thread starter mikeph
  • Start date Start date
  • Tags Tags
    Function General
AI Thread Summary
A user is developing a MATLAB function that requires a function handle for summing powers of a variable based on an input vector, which can vary in size. The specific example provided involves the vector [1, 2, 3], leading to the desired function handle f = @(x) [x^1 + x^2 + x^3]. The challenge is to create a general function handle that accommodates any N-by-1 vector without knowing its contents in advance. The solution proposed is f = @(x) sum(x.^v), which effectively addresses the requirement for variable input sizes. This approach successfully generates the desired functionality for the user's needs.
mikeph
Messages
1,229
Reaction score
18
I'm writing a MATLAB function m-file which has input argument of some N-by-1 vector.

Say this vector is [1,2,3].

I want to create a function handle representing a sum of x taken to the power of each number that appears in the vector, so in this case it is:

f = @(x) [x^1 + x^2 + x^3]; (x scalar)

The point is, I don't know how to define f when I don't explicitly know what the input vector is. Can anyone help me generate a general function handle? The trick is because N is variable.
 
Physics news on Phys.org
v=[1,2,3]

f = @(x) sum(x.^v)
 
I like it! Thanks very much
 

Similar threads

Replies
4
Views
1K
Replies
1
Views
3K
Replies
2
Views
2K
Replies
10
Views
2K
Replies
8
Views
3K
Replies
5
Views
3K
Back
Top