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?

 Réponse acceptée

Matt Fig
Matt Fig le 6 Août 2012
Modifié(e) : Matt Fig le 6 Août 2012

0 votes

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 commentaires

Matt Fig
Matt Fig le 6 Août 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 le 6 Août 2012
Welcome back Matt!
Chad Greene
Chad Greene le 6 Août 2012
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 le 6 Août 2012
Thanks, Oleg.
Matt Fig
Matt Fig le 6 Août 2012
Modifié(e) : Matt Fig le 6 Août 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 le 6 Août 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!

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by