How to convert cell array elements into one string, where elements are separated by comma

조회 수: 11 (최근 30일)
Hello,
I asked a solution for this problem, but I mistook the answer for good one, while I actually needed something slightly different. So I'll repeat myself a little bit again. I have a cell array which is:
legend_names(:)
ans =
'0.7 < T Days < 44.2'
'44.4 < T Days < 379.6'
'380.9 < T Days < 937.7'
'952.7 < T Days < 5040.0'
But I need this output to be one continuous string, where cell elements are separated with commas so I could use it to plot legend.
legend(histo_objects, legend_names(:)); Here histo_objects is 1xN line with saved plots.
I need result to be:
legend_names(:) = '0.7 < T Days < 44.2', '44.4 < T Days < 379.6', '380.9 < T Days < 937.7', '952.7 < T Days < 5040.0'
And I can't seem to get it.
(No comma after last one).
EDIT: I came up with some kind of solution myself, and it looks like this:
names = []; q = char(39); for i = 1:S
if i == 1
names = [ q legend_names{i} q ',' q];
elseif i < S
names = [ names legend_names{i} q ',' q];
elseif i == S
names = [ names legend_names{i} q ];
end
end
legend(plot_objects,names(:)');
Where:
names(:)'
ans =
'0.7 < T Days < 6.1','6.3 < T Days < 30.1','30.1 < T Days < 131.1','131.1 < T Days < 324.0','324.0 < T Days < 443.4','443.4 < T Days < 643.3','643.3 < T Days < 1027.0','1008.0 < T Days < 1770.0','1749.8 < T Days < 5040.0'
However, it does not work. It plots only one legend with all of chars in it. If I just copy text from names and write it manually into legend- it works. Why is it so ? Is there an easy way to get what I want with this result ?
  댓글 수: 2
Martynas Subonis
Martynas Subonis 2015년 11월 26일
Solved problem. Legend takes cell array of size 1xN. Cell array was simply created by:
for i = 1:S
period_matrix = Split_data_groups{i};
legend_names{i} = sprintf('%0.1f%s%0.1f', min(period_matrix(:,1)),' < T Days < ', max(period_matrix(:,1)));
end
There was no need for commas for this problem to begin with (apparently).
Star Strider
Star Strider 2015년 11월 26일
You don’t need the loop. My code does the same thing — efficiently — in three lines without a loop.

댓글을 달려면 로그인하십시오.

답변 (1개)

Star Strider
Star Strider 2015년 11월 26일
Does this do what you want?
Example code:
v = [0.7, 44.2; 44.4, 379.6; 380.9 937.7; 952.7, 5040.0];
LegStr = sprintf('%.1f < T Days < %.1f\n', v');
LegCell = regexp(LegStr, '\n', 'split');
x = linspace(0, 10);
figure(1)
plot(x, 1+2*x+0.1*randn(size(x)))
hold on
plot(x, 2-0.5*x+0.1*randn(size(x)))
plot(x, 5+0.1*x+0.1*randn(size(x)))
plot(x, -1+5*x+0.1*randn(size(x)))
hold off
grid
legend(LegCell(1:end-1))

카테고리

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