eval(['A = ',imtype,'​(abs(V*D*V​^(-1)));']​) ??? Error using ==> mtimes Logical inputs must be scalar.

What is the reason of error

2 Comments

Because using it leads to exactly this kind of error: impossible to bug fix. Because beginners think eval solves all of their problems, and so they stick it everywhere, and then get stuck with bugs like this. Because using eval removes all of the inbuilt code-checking that highlight syntax errors and give warnings about mistakes. Because eval is a poor tool for solving basic problems like this. Because eval is slow and pointless in this use case. Because eval obfuscates code intentions. Because you cannot click on those variables and let the editor show you their values, and highlight where they occur in the code. Because function tab-completion and dynamic help menus do not work with eval. Because instead of letting MATLAB help you to write your program, eval makes it more difficult. Because eval is an awful construct for assigning to variables. Because even the documentation clearly states that eval should be avoided:
"Code that calls eval is often less efficient and more difficult to read and debug than code that uses other functions or language constructs"
And now there is a bug that is hard to locate and debug... because of eval.
That is the error.
I wish I could upvote your comment. Post it as an answer for people to come and copy-paste your answer to other eval questions.

Sign in to comment.

Answers (1)

To trace down the error, please try
whos V
whos D
A = abs(V*D*V^(-1));
switch imtype
case 'double', A = double(A);
case 'uint8', A = uint8(A);
otherwise error(['Unknown imtype ' imtype '.'])
end
Based on Steven's remark, you can rewrite your code w/o eval as a one-liner:
A = cast(abs(V*D*V^(-1)), imtype);

2 Comments

You can replace the SWITCH block with a call to CAST, if you want to be able to handle more than just those two types.
Additionally, I would recommend to use / instead of ^(-1), i.e.
A = cast(abs(V*D/V), imtype);
Titus

Sign in to comment.

Tags

Asked:

on 2 Jul 2015

Commented:

on 2 Jul 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!