Reducing steps in code

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?

 采纳的回答

Matt Fig
Matt Fig 2012-8-6
编辑:Matt Fig 2012-8-6
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 个评论

Hi Lucas. No, the code I showed is not the same thing as the code you showed. With your code we have two new variables in the workspace.
Welcome back Matt!
Ha, indeed. You have correctly answered my question, but evidently I asked the wrong question! It's not the number of lines or variables that I care about, it's the number of steps. For the particular application I'm working on right now, I want to create a vector with a date range of say the year 1900 to this year. With d already defined I could accomplish this by
daterange = [1900 d(1)];
My question is, can I forget about pre-defining d altogether and have a single operation embedded within the daterange vector to look something like this:
daterange = [1900 specialoperationIdontknowgoeshere];
Thanks, Oleg.
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);
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!

请先登录,再进行评论。

更多回答(0 个)

类别

标签

Community Treasure Hunt

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

Start Hunting!

Translated by