Reducing steps in code

1 view (last 30 days)
Chad Greene
Chad Greene on 6 Aug 2012
Is there a way to create a vector and take only the nth value of that vector, all in one line? For example if I wanted to return the current year I could easily do it in two lines:
d = datevec(date);
y = d(1);
Can I do this without first defining d?

Accepted Answer

Matt Fig
Matt Fig on 6 Aug 2012
Edited: Matt Fig on 6 Aug 2012
Sure we can get y in one line without defining d!
clear all
y = datevec(date); y = y(1); % Here's the 1 line!
whos
  6 Comments
Matt Fig
Matt Fig on 6 Aug 2012
Edited: Matt Fig on 6 Aug 2012
Lucas, I realize what Chad wants; this is a perennial question for The MathWorks. As of now there is no way to index into an array before it is created in the workspace. If the function returns an array, we have to take the array as is. Until further notice. This is the reason people came up with tricks like I showed. We can overwrite the original array to save memory but that is about the best we can do so far.
Another thing one can do is create a custom function, but this still doesn't avoid the main problem but hides it.
function d = mydatevec(varargin)
d = datevec(varargin);
d = d(1);
Chad Greene
Chad Greene on 6 Aug 2012
Matt, that's not the answer I was hoping for, but it is a very clear answer to a question I've had for years. Thanks for your help!

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Identification in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!