Search code examples
matlablegendcell-array

making legend from a cell array in matlab


I think my problem may be quite common, but I did not find an answer. Maybe I am looking at this the wrong way!? How can I end up making a legend from this type of matrix:

X =

[4.4200e+09]    [ 600]    [ 8]    'm2 hard hm (50)' 
[4.4200e+09]    [ 600]    [ 8]    'm3 hard hm (52)' 
[4.4200e+09]    [ 600]    [ 8]    'm2 soft hm (56)' 
[4.4200e+09]    [ 600]    [ 8]    'm3 soft hm (58)' 
[4.4200e+09]    [ 600]    [ 8]    'm2 hard hm (50)' 
[4.4200e+09]    [ 600]    [ 8]    'm3 hard hm (52)' 
[4.4200e+09]    [ 600]    [ 8]    'm2 soft hm (56)' 
[4.4200e+09]    [ 600]    [ 8]    'm3 soft hm (58)' 
[4.4200e+09]    [1000]    [25]    'm3 hard hex (53)'
[4.4200e+09]    [1000]    [25]    'm3 soft hex (59)'

where the length of the digits may vary, and the number of rows varies to...

class(X)
ans =
cell

When I write legend(X) matlab complaints. I have tried to solve the problem with sprintf using a loop like

sprintf('%d %d %d %s',X{ind,:})

ans =

4420012257 600 8 m2 hard hm (50)

where ind increments, but then I get the problem that the size may vary (some digits are longer)

The data that should be plotted is in two matricies. So I am looking at ending up with something like:

plot(t,y); legend(X)

Appreciate any help!


Solution

  • Given:

    X = {[4.4200e+09]    [ 600]    [ 8]    'm2 hard hm (50)' 
    [4.4200e+09]    [ 600]    [ 8]    'm3 hard hm (52)' 
    [4.4200e+09]    [ 600]    [ 8]    'm2 soft hm (56)' 
    [4.4200e+09]    [ 600]    [ 8]    'm3 soft hm (58)' 
    [4.4200e+09]    [ 600]    [ 8]    'm2 hard hm (50)' 
    [4.4200e+09]    [ 600]    [ 8]    'm3 hard hm (52)' 
    [4.4200e+09]    [ 600]    [ 8]    'm2 soft hm (56)' 
    [4.4200e+09]    [ 600]    [ 8]    'm3 soft hm (58)' 
    [4.4200e+09]    [1000]    [25]    'm3 hard hex (53)'
    [4.4200e+09]    [1000]    [25]    'm3 soft hex (59)'}
    

    You can use an implicit loop, specifying that the output of each iteration is stored in a cell, i.e. with 'UniformOutput', false (equivalently 'un',0):

    X = arrayfun(@(ii) sprintf('%d %d %d %s',X{ii,:}), 1:size(X,1), 'un',0)';
    

    The arrayfun is equivalent to:

    nrows = size(X,1);
    s = cell(nrows,1);
    for ii = 1:nrows
        s{ii} = sprintf('%d %d %d %s',X{ii,:});
    end