Troubleshooting Matlab Script with User-Input Function | Beginner's Guide

  • Context: MATLAB 
  • Thread starter Thread starter c299792458
  • Start date Start date
  • Tags Tags
    Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
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!
 
Physics news on Phys.org
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)