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

  • Context: MATLAB 
  • Thread starter Thread starter c299792458
  • Start date Start date
  • Tags Tags
    Matlab
Click For Summary
SUMMARY

This discussion focuses on troubleshooting a MATLAB script that utilizes a user-input function, f(x). The user initially attempts to define f(x) as an anonymous function using the syntax f = @(x) input('Enter f(x): '), which leads to repeated prompts during an iterative While loop. A more effective approach is suggested, where the function is entered as a string and executed using the eval() function. This method allows for seamless integration of user-defined functions without repeated input prompts.

PREREQUISITES
  • Familiarity with MATLAB scripting
  • Understanding of anonymous functions in MATLAB
  • Knowledge of the eval() function in MATLAB
  • Basic concepts of iterative loops in programming
NEXT STEPS
  • Explore the use of MATLAB anonymous functions in depth
  • Learn about the implications and best practices of using eval() in MATLAB
  • Research alternatives to user-input functions in MATLAB for better performance
  • Investigate MATLAB's function handles and their applications
USEFUL FOR

This discussion is beneficial for MATLAB users, particularly beginners and intermediate programmers, who are looking to enhance their scripting skills and understand user-input function handling in MATLAB.

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 ·
Replies
1
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 19 ·
Replies
19
Views
2K
Replies
4
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 14 ·
Replies
14
Views
4K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K