simpler way to make new matlab function compatible to early version
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Rik
el 10 de Feb. de 2017
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
Respuestas (2)
Honglei Chen
el 10 de Feb. de 2017
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 comentarios
Xiangrui Li
el 10 de Feb. de 2017
1 comentario
Rik
el 11 de Feb. de 2017
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).
Ver también
Categorías
Más información sobre Argument Definitions en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!