How do I print a legend using a character array and integer array?

4 ビュー (過去 30 日間)
Shelley Snider
Shelley Snider 2023 年 1 月 18 日
コメント済み: Fangjun Jiang 2023 年 1 月 19 日
I want to print a legend that looks like this:
1st entry: 'Current solution, 4800 m DR'
2nd entry: 'Current solution, 7000 m DR'
3rd entry: 'Current solution, 9000 m DR'
4th entry: 'Archive solution, 4800 m DR'
5th entry: 'Archive solution, 7000 m DR'
6th entry: 'Archive solution, 9000 m DR'
The numbers come from a structure array. I'm trying to use sprintf, but I'm having troubles with the format of the 'Current' and 'Archive' strings. A character array does not work since sprintf iterates through each character instead of each word. Do I need to do a cell array and then do a comma separated list for that?
  1 件のコメント
Walter Roberson
Walter Roberson 2023 年 1 月 19 日
A character array does not work since sprintf iterates through each character instead of each word.
A = 'Current'
A = 'Current'
sprintf('->%s<-', A)
ans = '->Current<-'
sprintf('->%c<-', A)
ans = '->C<-->u<-->r<-->r<-->e<-->n<-->t<-'
You were using the wrong format item.

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

採用された回答

Stephen23
Stephen23 2023 年 1 月 19 日
COMPOSE() is perfect for this, but was first introduced in R2016b. You could use ARRAYFUN() or CELLFUN():
C = {'Current','Current','Current','Archive','Archive','Archive'};
V = [4800,7000,9000,4800,7000,9000];
fnh = @(t,n)sprintf('%s solution, %d m DR',t,n);
lgd = cellfun(fnh,C(:),num2cell(V(:)), 'uni',0)
lgd = 6×1 cell array
{'Current solution, 4800 m DR'} {'Current solution, 7000 m DR'} {'Current solution, 9000 m DR'} {'Archive solution, 4800 m DR'} {'Archive solution, 7000 m DR'} {'Archive solution, 9000 m DR'}

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2023 年 1 月 18 日
編集済み: Fangjun Jiang 2023 年 1 月 18 日
a="current";
b={'archive'};
c='current';
sprintf('%s',a)
ans = 'current'
sprintf('%s',b{1})
ans = 'archive'
sprintf('%s',c)
ans = 'current'
  2 件のコメント
Shelley Snider
Shelley Snider 2023 年 1 月 18 日
I'm looking for something that prints the list of entries in my question.
Fangjun Jiang
Fangjun Jiang 2023 年 1 月 19 日
Use a for-loop, or use the cellfun() that @Stephen23 demonstrated.
Another trick is below, if you put the data in the right format
data={'1st','2nd','3rd';'Current','Archive','Current';4800,7000,9000};
sprintf('%s entry: ''%s solution, %d m DR''\n',data{:})
ans =
'1st entry: 'Current solution, 4800 m DR' 2nd entry: 'Archive solution, 7000 m DR' 3rd entry: 'Current solution, 9000 m DR' '

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

カテゴリ

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

タグ

製品


リリース

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by