How do I build a cell array of strings?

조회 수: 87 (최근 30일)
Jim
Jim 2013년 3월 27일
편집: Randy Souza 2013년 10월 29일
I am trying to build a cell array of strings that can be used as legend text in a plot. A simplified version of what I am trying to do is as follows:
legends = '';
legends = 'this';
legends = {legends; 'this other one'};
legends = {legends; 'this here one here'};
legends = {legends; 'and this other one'};
legend(legends, 'Location', 'SouthOutside');
However, I receive the following error on the legend command:
Cell array argument must be a cell array of strings.
I thought {} were used to generate a cell array of strings. Why is this not working?

채택된 답변

Todd
Todd 2013년 3월 27일
Hi Jim,
Remember that cell arrays can hold arbitrary data (including other cell arrays) and that while [] is concatenate, {} is "build a cell array". From the documentation about {}:
"Braces are used to form cell arrays. They are similar to brackets [ ] except that nesting levels are preserved."
Therefore, after your fourth assignment to legends, you actually have a cell array containing two elements, a cell array and a string.
Instead, consider using:
>> legends = {'first'}
legends =
'first'
>> legends(end+1) = {'second'}
legends =
'first' 'second'
>> legends(end+1) = {'third'}
legends =
'first' 'second' 'third'
Even better yet, if you know all the strings ahead of time, generate it all at once such as:
legends = {'first' ...
'second' ...
'third'}
legends =
'first' 'second' 'third'
todd

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by