Error using eval function
Show older comments
I am trying simple eval function . But at some times it gets executed fine. Sometimes it gives me the error msg "Error: Unexpected MATLAB expression". Here's the eval function code. I hope i got the syntax correctly. collection is a character array = 'hero','zero','horse','cow'
collection = regexprep(collection,' ',''',''');
eval(['words = {''',collection,'''};']);
2 Comments
Lets have a look at your question in detail, because it is a good example of why using eval is a poor way to write code:
"I am trying simple eval function."
That is the bad design decision right here.
"But at some times it gets executed fine. Sometimes it gives me the error msg "Error: Unexpected MATLAB expression"."
Notice how the message is not very helpful. Because you used eval it cannot show you the line or particular code position where the error occurs. By using eval you just made debugging much more difficult.
"Here's the eval function code. I hope i got the syntax correctly."
If you had written your code normally without eval then the MATLAB editor would highlight any syntax errors and even suggest how to fix them. And of course the editor also offers tab completion, variable highlighting, etc. etc. When you decided to use eval none of these features work, so you just picked a way of writing code that make it harder for you to write good code. And harder to debug it!
Summary: you picked a way of writing code that is slow, buggy, hard to debug, and obfuscates the code intent. You then found your code to be buggy and hard to debug. Even though what you are attempting is actually trivially simple because you used eval it was too difficult for you to fix by yourself, and you had to ask random strangers to help you.
All of this could have been avoided very simply: by not using eval. Read this to know some of the reasons why:
HIRAKJYOTI BASUMATARY
on 21 Dec 2017
Accepted Answer
More Answers (0)
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!