MATLAB [Matlab] Function Handle-user input

AI Thread Summary
In the discussion, the main question revolves around using user inputs to create function handles in Matlab. The user attempts to prompt for a function in terms of 'x' and then create a handle with the input. However, they encounter an error indicating that 'x' is undefined. Responses clarify that users must input a complete function handle rather than just a part of it. If a user inputs a number or a matrix, the resulting handle does not function as intended. The analogy provided compares this situation to the impossibility of creating a matrix that is simultaneously of two different types, emphasizing the need for a valid function handle as a fundamental type in Matlab.
Bostonpancake0
Messages
42
Reaction score
0
Hi,

My question is in relation to Matlab.

I'm curious, is there anyway to employ user inputs for function handles?

By this I mean that the user is prompted to enter they're chosen function and the next line of code employs that into a handle.

My quick and rough attempt was:

a=input('enter a function in terms of x: ')
f=@(x) a

But I receive an error saying "Undefined function or variable x"

Any suggestions greatly appreciated.
 
Physics news on Phys.org
I don't think that's possible. They would have to input the entire function handle, not just a piece.

Otherwise, what is a? If they input a number, or a matrix, then "@(x) a" just returns a, and isn't really a function. If they input a string like 'sin', then "@(x) a" just doesn't make any sense. They need to input a function handle, since it is a fundamental type.

It would be similar to asking, "Input a matrix that is half int32 and half double." Not possible. Matrices can be entirely int32 or entirely double, but not both.
 

Similar threads

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