Home > Blockchain >  How do I resolve an "Invalid use of operator" error in an input function?
How do I resolve an "Invalid use of operator" error in an input function?

Time:06-26

I am writing a code that requires the user to input a specific file directory (which they can obtain by hitting copy address as text when in the corresponding file). The line of code looks like this and it occurs near the very beginning of the code:

folder = input('Input file location (Copy address as text) \n(i.e. C:\\Users\\joahf\\Documents\\MATLAB\\Image Processing\\image_sets\\software_setup): '); % Have user input file location.

When I run the code, this is what I input and the corresponding error that occurs:

1

The code ends instantly after submitting this input.

The code continues to run fine when I do not input anything and the input functions returns an empty matrix. Even stranger, when I input something simpler such as "hello", I get a different error and it allows me to reenter it:

2

If someone knows what could be going on that would be much appreciated.

CodePudding user response:

Aisde: You should consider using uigetfile or uigetdir which are better suited to inputting file paths than input.

To answer the actual question, input evaluates the input string as code (i.e. pipes it into eval), which makes it pretty dangerous for anything "customer-facing". From the docs:

x = input(prompt) displays the text in prompt and waits for the user to input a value and press the Return key. The user can enter expressions, like pi/4 or rand(3), and can use variables in the workspace.

If the user presses the Return key without entering anything, then input returns an empty matrix.

If the user enters an invalid expression at the prompt, then MATLAB® displays the relevant error message, and then redisplays the prompt.

Emphasis mine, the final sentence shows exactly what you're seeing, it is either trying to evaluate a file path as code and erroring with an invalid operator usage (likely referring to the colon near the start or one of the slashes which aren't doing what they normally do in MATLAB) or erroring and re-prompting when you enter something without an operator (like hello).

You need to use the 2nd usage example from the docs:

txt = input(prompt,'s') returns the entered text, without evaluating the input as an expression.

You can use "s" (string) or 's' (char) equivalently.

  • Related