How do you enforce Element-wise operations in function handles?
34 次查看(过去 30 天)
显示 更早的评论
I am looking to enforce that all function handles enforce elementwise operations. The reason for this is I have written a 3D numerical integration scheme which can only compute the correct answer with these types of functions.
What I want is for any user who inputs a function say
func = @(x,y,t) x*y*t
will automatically change to,
func = @(x,y,t) x.*y.*t
Essentially I need to check the function for elementwise operations and then change it to them if neccessary. I would also like to avoid the symbolic package all together if possible.
Any help would be appreciated.
0 个评论
回答(2 个)
Star Strider
2021-4-2
I will be roundly criticized for suggesting the vectorize function. I have no idea why it is ‘Not recommended’ since in situations such as yours, it is useful. It would be relatively straightforward to write your own version of it, however so long as it continues to exist, I would use it. (I sometimes use it to do element-wilse operations on long expressions I find in Questions here, since it is easier than going through the expressions manually and vectorizing every operation, or writing my own function to do exactly what vectorize does.)
1 个评论
Stephen23
2021-4-2
编辑:Stephen23
2021-4-2
"I have no idea why it is ‘Not recommended’ since in situations such as yours, it is useful."
My guess is because it operates on text, which since the introduction of function handles has been discouraged as a means for storing functions:
"In addition, code is generally more robust with function handles instead of strings for representing functions."
Stephen23
2021-4-2
编辑:Stephen23
2021-4-2
There is no trivial answer to this. Fundamentally your request involves swapping operators, just as if you requested to replace COS with SQRT: this is unlikely to be trivial, if it is at all possible in the general case. Note that converting to string (e.g. in order to use VECTORIZE) will immediately lose all bindings to local variables and local functions that were within scope when the function handle was defined, so that is also not a general solution.
AFAIK, the most general approach is to just call the function multiple times. You can easily write a wrapper function which returns a function which contains a loop (calling your input function). It would be reasonably efficient.
Or using an anonymous function wrapper (less efficient than a loop):
func = @(x,y,t) x*y*t;
fun = @(varargin)arrayfun(func,varargin{:}); % wrap
fun(1:3,4:6,7:9)
The same as a function which can be applied as many times you want, e.g.:
wrap = @(f)@(varargin)arrayfun(f,varargin{:});
fun = wrap(func); % wrap
fun(1:3,4:6,7:9)
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!