convert number to string problem

6 ビュー (過去 30 日間)
Yu Li
Yu Li 2019 年 3 月 10 日
コメント済み: Yu Li 2019 年 3 月 10 日
I have a column number, and I want to add some string in front of it, and assign it to items of a drop-down list in an App.
take the test value test=1:1:5 for example, below is my code:
test=1:1:5;
for i=1:1:length(test)
tmp_name{i}=strcat('Data Set',num2str(test(i)));
end
to improve this code without the for-loop, I found that there is a function 'num2cell' but it does not work in this case:
test=1:1:5;
strcat('CVG Set',num2cell(test))
below is the result:
Capture.JPG
the numbers are converted to a rectangle symbol instead of string.
is there any mistake with my operation?
Bests,
Yu

採用された回答

madhan ravi
madhan ravi 2019 年 3 月 10 日
sprintfc('Data Set %d',test) % beware undocumented
  2 件のコメント
madhan ravi
madhan ravi 2019 年 3 月 10 日
Alternative:
cellstr("Data set "+test)
Yu Li
Yu Li 2019 年 3 月 10 日
Thank you.
Bests,
Yu

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

その他の回答 (2 件)

Geoff Hayes
Geoff Hayes 2019 年 3 月 10 日
Yu - I think the problem might be because when you use num2cell, you are creating a cell array of numbers and not a cell array of strings.
An alternative to what you have written is to use arrayfun where we apply a function to each of our integers (in test). For example,
tmp_name = arrayfun(@(x)sprintf('CVG Set %d',x),1:5, 'UniformOutput', false);
initializes the variable to
tmp_name =
'CVG Set 1' 'CVG Set 2' 'CVG Set 3' 'CVG Set 4' 'CVG Set 5'
which may be sufficient for what you need. You can modify the string in the sprintf call to get a different format (if that is what you need).
  1 件のコメント
Yu Li
Yu Li 2019 年 3 月 10 日
Thank you.
Bests,
Yu

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


Image Analyst
Image Analyst 2019 年 3 月 10 日
Yu:
Try this:
test = 1 : 5;
for k = 1 : length(test)
popupStrings{k} = sprintf('Data Set %d', test(k));
end
celldisp(popupStrings)
% Now load the strings into the popup (drop down list)
handles.popup1.String = popupStrings;
  2 件のコメント
madhan ravi
madhan ravi 2019 年 3 月 10 日
OP tries to avoid a for-loop.
Yu Li
Yu Li 2019 年 3 月 10 日
Thank you.
Bests,
Yu

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

カテゴリ

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