MATLAB function prompts repeatedly in while loop

  • Topic: MATLAB 
  • Thread starter c299792458
  • Start date
  • Tags Tags
    Matlab
1 reply · 3K views · last reply
c299792458
Messages
67
Reaction score
0
Hi,

I am attempting to write a Matlab script that uses a user-input (hence general) function, f(x), throughout the script. I thought of using he following:

f = @(x) input('Enter f(x): ')

but then when my (iterative) While loop is executed which contains (f(x)), the prompt pops up after every cycle.

I'd be grateful for any help!
 
The anonymous function syntax is a fairly recent addition to matlab. Traditionally you could have entered the function as a string and used the MATLAB "eval" function to execute it.

Something like this,
Code:
! Enter the function as a string
fs = input("Enter a function of x > ",'s')

! "Call" the function using the compound assign x and then eval().
! for example enter "x.^3 - 5" for the above (quotes not needed
! as its expecting a string) and then test it with ...
x=5; eval(fs)
! Returns 115 as expected for f(5)