Explicitly numbered string?

13 ビュー (過去 30 日間)
nilsotto
nilsotto 2016 年 2 月 28 日
コメント済み: nilsotto 2016 年 2 月 28 日
Hi,
How do I explicitly define a string with numbering? Look at the example below. Suppose "numbers" are unknown and I want to name the figures Q1, Q2 etc.
numbers=3;
fname={'Q1' 'Q2' 'Q3'};
for i=1:numbers
if i==1
x = -2*pi:0.01:2*pi;
elseif i==2
x = -3*pi:0.01:3*pi;
else
x = -4*pi:0.01:4*pi;
end
y = sin(x);
h=figure
plot(x,y);
print(h,'-dpng',fname{1,i});
end

回答 (2 件)

Guillaume
Guillaume 2016 年 2 月 28 日
My recommendation is to use sprintf which lets you compose any arbitrary string that you want.
fnames = cell(1, numbers);
for i = 1:numbers
fname{i} = sprintf('Q%d', i);
end
Or as a one-liner:
fnames = cellfun(@(n) sprintf('Q%d', n), 1:numbers, 'UniformOutput', false);
Note that the format string of sprintf is very flexible. If you had more than 10 numbers and wanted to generate: Q01, Q02, ..., Q10, etc.:
sprintf('Q%02d', i)
  2 件のコメント
Jan
Jan 2016 年 2 月 28 日
Unfortunately undocumented yet:
fnames = sprintfc('Q%d', 1:numbers)
nilsotto
nilsotto 2016 年 2 月 28 日
Many thanks guys!

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


Azzi Abdelmalek
Azzi Abdelmalek 2016 年 2 月 28 日
numbers=3;
fname=genvarname(repmat({'Q'},1,numbers),'Q')
for ii=1:numbers
x = -(ii+1)*pi:0.01:(ii+1)*pi;
y = sin(x);
h=figure
plot(x,y);
print(h,'-dpng',fname{ii});
end
  1 件のコメント
Guillaume
Guillaume 2016 年 2 月 28 日
While genvarname would work in this case, it's not for generating abritrary strings, only valid variable names. The set of valid filenames is much greater than the set of valid variable names.

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

カテゴリ

Help Center および File ExchangeString についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by