Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab Newbie Troubleshoot

  1. Aug 7, 2011 #1

    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!
  2. jcsd
  3. Aug 8, 2011 #2


    User Avatar
    Science Advisor

    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 (Text):

    ! 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)
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook