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일

0 개 추천

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

Matt Fig
Matt Fig 2012년 8월 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.
Oleg Komarov
Oleg Komarov 2012년 8월 6일
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 2012년 8월 6일
Thanks, Oleg.
Matt Fig
Matt Fig 2012년 8월 6일
편집: Matt Fig 2012년 8월 6일
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 2012년 8월 6일
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개)

카테고리

도움말 센터File Exchange에서 Pie Charts에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by