Function Handle Constructor
Jiro‘s pick this week is function_handle constructor by Rody Oldenhuis.
When I first started programming in MATLAB, I would create my MATLAB files (scripts, functions) in my current folder. Everything is there, so I had no issues calling my scripts and functions. As I started working on multiple projects, I would create a new working folder and put everything there. After a while, I would have these similar functions that I constantly reuse. That was around the time I learned about the path. I can put all of my utility functions in a particular folder and add that folder to my search path. Later on, I learned about other ways of organizing my code, like private functions. When I learned about object oriented programming, I discovered the existence of packages.
Once in a while, I have these situations where I need to call a function that lives in some other folder, but that folder is not on the path. I just need it for that particular task, and I don’t want to add it to the path just for that task. There is a handy function called run, which allows you to call any script that exist elsewhere, but it doesn’t work for functions. This is where function_handle by Rody comes into play.
For example, there was a blog post I did a few years ago where I highlighted an entry that converted numbers to English names. The function isn’t on my path, but let me show you how it works. First, I’ll create a function handle for that function. Normally, you just use the @ symbol to create a function handle. But for a function that is not on the path, it becomes a bit tricky. Here, I’ll use Rody’s function_handle.
fcn = function_handle('..\2015_01_09_Num2Words\num2words\num2words.m')
fcn = function_handle with value: @num2words
Now I can just call num2words using the function handle.
fcn(1024)
ans = 'one thousand and twenty-four'
Comments
Give it a try and let us know what you think here or leave a comment for Rody.
- 범주:
- Picks
댓글
댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.