Generate and Increment var names containing numbers and strings

41 ビュー (過去 30 日間)
Dee
Dee 2014 年 2 月 13 日
コメント済み: Matt Tearle 2014 年 2 月 13 日
Hello,
I'd like to generate a list of variable names where the output looks as follows:
# TB1W082A
# TB1W083A
# TB1W084A
# TB1W08AA
# TB1W08BA
# TB1W08CA
# TB1W092A
# TB1W093A
# TB1W094A
# TB1W09AA
# TB1W09BA
# TB1W09CA
Here is the code I'm using:
% alph=('A':'C');
% for n1 = 8:9
for n2 = 1:3
for a = 1:3
num{n2} = ['TB1W' num2str(n1) num2str(n2+1) 'A'];
str{a} = ['TB1W' num2str(n1) alph(a) 'A'];
end
end
end
clear a alpha n1 n2
I tried creating two variables; num and str. One was meant for the numeric portion and the other for the alphabetic portion. However, this is the output I get:
num =
  1. TB1W092A
  2. TB1W093A
  3. TB1W094A
str =
  1. TB1W09AA
  2. TB1W09BA
  3. TB1W09CA
Any suggestions?
  1 件のコメント
dpb
dpb 2014 年 2 月 13 日
Yeah, don't...see
for why not and how to do "the Matlab way" or if insist even the evil eval

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

採用された回答

Matt Tearle
Matt Tearle 2014 年 2 月 13 日
編集済み: Matt Tearle 2014 年 2 月 13 日
See dpb's comment on why creating variable names like this is a bad idea, but... assuming you have a valid reason for creating strings in such a pattern:
Firstly, how general does this need to be? The twelve strings in your example are easily done with
x = {'2';'3';'4';'A';'B';'C'};
names = [strcat('TB1W08',x);strcat('TB1W09',x)]
Slightly more generally:
pre = 'TB1W';
names = {};
for k = 7:12
names = [names;strcat([pre,num2str(k,'%02d')],x)];
end

その他の回答 (1 件)

Dee
Dee 2014 年 2 月 13 日
Matt,
Thanks for volunteering your time. Your solution works very well. I guess I'm still baffled about why the embedded for loops didn't work. I guess that serves me right for trying to use so many of them. Thanks again.
  1 件のコメント
Matt Tearle
Matt Tearle 2014 年 2 月 13 日
The problem was that you were using your loop variables a and n2 as the indices to your arrays, so you are only ever assigning num{1}, num{2}, and num{3} (and ditto str). You were actually assigning them multiple times each, repeatedly overwriting them. To make your approach work, you'd need to keep an overall count variable going. Something along the lines of
k = 1;
for ...
for ...
for ...
num{k} = ...
k = k+1;
end
end
end

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by