Store Variable name as Sequence 't1', 't2', 't3',.......

I have a problem naming my VariableNames in my array2table.
years={'t1','t2','t3','t4','t5','t6','t7','t8','t9','t10','t11','t12','t13','t14','t15','t16','t17','t18','t19','t20'};
I = array2table(A,'VariableNames', years)
Is there any other way to make a sequence for years? My end date t20 can vary and I don't want to change the variablename each time I want to change my end date.

8 件のコメント

Dennis
Dennis 2018 年 5 月 8 日
As a rule of thumb, when you are typing x1,x2,x3 ... you are usually doing something wrong ;)
for ii=1:size(A,2)
years{ii}=strcat('t',num2str(ii));
end
Stephen23
Stephen23 2018 年 5 月 8 日
編集済み: Stephen23 2018 年 5 月 8 日
@Dennis: why is this? I don't see any code or efficiency disadvantages for naming table variables like this. Certainly the names could be more descriptive... but what are the problems that you foresee with this?
It seems to me that years would normally be rows of a table (rather than variables), which would allow processing and grouping of the data by year.
Dennis
Dennis 2018 年 5 月 8 日
I think it is not very efficient to type numbers from 1 to 20, do you think its still a viable option for 1 to 200?
Stephen23
Stephen23 2018 年 5 月 8 日
編集済み: Stephen23 2018 年 5 月 8 日
@Dennis: Why would I need to type them all out? Any of compose, or arrayfun, or (the sadly undocumented) sprintfc can easily generate those names for me, as well as other fancy methods using sprintf and split or regexp. Or your nice little loop.
Dennis
Dennis 2018 年 5 月 8 日
That was exactly my point? You shouldnt type x1,x2,x3...
Stephen23
Stephen23 2018 年 5 月 8 日
@Dennis: aaahhh... so it was just the "lots of typing" that you were commenting on, not the name format itself?
Dennis
Dennis 2018 年 5 月 8 日
yes, sorry if i wasn't clear.
Cinko
Cinko 2018 年 5 月 8 日
@Dennis That works great. Thank you.

サインインしてコメントする。

回答 (1 件)

Guillaume
Guillaume 2018 年 5 月 8 日

0 投票

years = compose('t%d', 1:20);

3 件のコメント

Cinko
Cinko 2018 年 5 月 8 日
that gives the error: Undefined function 'compose' for input arguments of type 'char'.
Guillaume
Guillaume 2018 年 5 月 8 日
編集済み: Guillaume 2018 年 5 月 8 日
compose requires R2016b or later. You must be on an earlier version. You can use sprintfc instead but be aware that this function is undocumented
years = sprintfc('t%d', 1:20); %note that sprintfc is undocumented. In this case, it behaves like compose introduced in R2016b
If using undocumented functions is not your thing, then
years = arrayfun(@(n) sprintf('t%d', n), 1:20, 'UniformOutput', false);
Cinko
Cinko 2018 年 5 月 8 日
okay thank you

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

タグ

質問済み:

2018 年 5 月 8 日

編集済み:

2018 年 5 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by