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

  • Thread starter Thread starter c299792458
  • Start date Start date
  • Tags Tags
    Matlab
AI Thread Summary
The discussion focuses on creating a user-input function in a MATLAB script that can be utilized within an iterative loop. The initial approach using an anonymous function with the syntax f = @(x) input('Enter f(x): ') leads to repeated prompts during each iteration of the loop. A suggested solution involves using a string input for the function, allowing the user to enter a function of x as a string and then employing the eval function to execute it. This method enables the user to input a function like "x.^3 - 5" and test it with a specific value of x, providing the expected output without repeated prompts.
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)
 

Similar threads

Replies
1
Views
3K
Replies
3
Views
3K
Replies
3
Views
4K
Replies
1
Views
2K
Replies
1
Views
3K
Back
Top