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?

 Risposta accettata

Matt Fig
Matt Fig il 6 Ago 2012
Modificato: Matt Fig il 6 Ago 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 Commenti

Matt Fig
Matt Fig il 6 Ago 2012
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.
Oleg Komarov
Oleg Komarov il 6 Ago 2012
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];
Matt Fig
Matt Fig il 6 Ago 2012
Thanks, Oleg.
Matt Fig
Matt Fig il 6 Ago 2012
Modificato: Matt Fig il 6 Ago 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 il 6 Ago 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!

Accedi per commentare.

Più risposte (0)

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by