simpler way to make new matlab function compatible to early version
1 次查看(过去 30 天)
显示 更早的评论
flip is a builtin function for later matlab, but not for earlier matlab. I am thinking this simple way to take care of the compatibility:
if ~exist('flip', 'builtin'), flip = @(img,dim) flipdim(img,dim); end
The idea is to use builtin flip if available, otherwise create a handle to call flipdim for earlier matlab.
This works fine if flip is not builtin, but fails when flip is builtin function with error "Undefined function or variable 'flip'."
Interestingly, the error only happens in a function, while it works in script. It seems, in a function, even if the above 'if' statement is false, matlab still thinks flip as a variable, and throw the error during run time.
I know I can do try flip catch flipdim to take care of this, but if flip is called multiple times in a function, the above one-line check will be much cleaner.
Is there a way to not let matlab think flip is a variable when flip exists as builtin?
Thanks.
-Xiangrui
1 个评论
Rik
2017-2-10
I don't have a real solution, but maybe you can fix the symptoms with
if ~exist('flip', 'builtin')
flip_wrap = @(img,dim) flipdim(img,dim);
else
flip_wrap = @(img,dim) flip(img,dim);
end
回答(2 个)
Honglei Chen
2017-2-10
I believe in a function, MATLAB does some static analysis so it sees flip first as a variable, even though it represents an anonymous function. On the other hand, in a script, the parsing is done at the run time so the engine can get to the desired function on spot.
HTH
0 个评论
Xiangrui Li
2017-2-10
1 个评论
Rik
2017-2-11
I got a wrap on the knuckle for suggesting the use of eval, zo I'm going to copy the comment written by Guillaume (although I personally think it should be treated as a for-loop: inelegant, slow, avoid if possible):
We're against the use of eval because it encourages poor coding practices. You lose at lot by using eval:
- tab completion
- syntax highlighting
- mlint autodetection of errors, warnings. A misspelling of a variable name, or invalid function use won't be detected by the code editor.
- speed, because the JIT compiler has no way to know what happens inside eval it can't pre-compile or optimise the function codeautomatic renaming of all instances of a variable/function, when you rename one instance. Won't work for the occurences inside eval.
- clarity, it's much harder to understand code that has extra num2str, string concatenation, etc.
With eval, you're adding an extra layer on top of your code. This should be avoided at all cost unless there's absolutely no other way (which is extremely rare).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!