MATLAB Release 2009b – Best New Feature or ~?
MATLAB R2009b was recently released. My favorite new language feature is the introduction of the ~ notation to denote missing inputs in function declarations, and missing outputs in calls to functions. Let me show you how this works.
I have occasionally found that I would like the indices from sorting a vector, but I don't need the sorted values. In the past, I wrote one of these code variants :
[dummy, ind] = sort(X) [ind, ind] = sort(X)
In the first case, I end up with a variable dummy in my workspace that I don't need. If my data to sort, X, has a large number of elements, I will have an unneeded large array hanging around afterwards. In the second case, I am banking on MATLAB assigning outputs in order, left to right, and I create somewhat less legible code, but I don't have an extra array hanging around afterwards.
Now you can write this instead:
[~, ind] = sort(X)
and I hope you find your code readable, with the clear intention to not use the first output variable.
You can similarly designate unused inputs with ~ in function declarations. Here's how you'd define the interface where the second input is ignored.
function out = mySpecialFunction(X,~,dim)
You might ask why that is useful. If I don't use the second input, why put it in at all? The answer is that your function might be called by some other function that expects to send three inputs. This happens for many GUI callbacks, and particularly those you generate using guide. So your function needs to take three inputs. But if it is never going to use the second input, you can denote the second one with ~.
Can M-Lint Help?
Yes! Consider this function mySpecialFunction shown here.
function ind = mySpecialFunction(X,second,dim) % mySpecialFunction Function to illustrate ~ for inputs and outputs. [dummy,ind] = sort(X,dim);
Running mlint on this code produces two messages.
msgs = mlint('mySpecialFunction'); disp(msgs(1).message(1:50)) disp(msgs(1).message(51:end)) disp(' ') disp(msgs(2).message(1:49)) disp(msgs(2).message(50:end))
Input argument 'second' might be unused, although a later one is used. Consider replacing it by ~. The value assigned here to 'dummy' appears to be unused. Consider replacing it by ~.
Since M-Lint is running continuously in the editor, you would see these messages as you edit the file. Here's a cleaned up version of the file.
function ind = mySpecialFunction1(X,~,dim) % mySpecialFunction Function to illustrate ~ for inputs and outputs. [~,ind] = sort(X,dim);
And let's see what M-Lint finds.
It finds nothing at all.
What's Your Favorite New Feature?
Have you looked through the new features for R2009b? What's your favorite? Let me know here.
댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.