0

When attempting to assign VariableNames to table columns when using array2table I am getting the error:

Error using array2table (line 62)
The VariableNames property must be a cell
array, with each element containing one
nonempty string.

This error however only occurs when using a cell-array constructed using strcat or sprintf, for example:

for p=1:length(b)
    string{p,:} = {strcat(a,num2str(b(p)))};
end

string = 

    {1x1 cell}
    {1x1 cell}
    {1x1 cell}
    {1x1 cell}

Whereas, assigning the VariableNames directly:

T = array2table(ncoIED,'VariableNames',{'A' 'B' 'C' 'D'});

Works as intended.

This seems to be down to the way the strings are stored in the cell-array - each string is surrounded by ' ' whereas a = {'A' 'B' 'C' 'D'}; does not add this.

I need to be able to dynamically create string names by concatenating multiple variables - is there a way to do this that will be compatible with the VariableNames parameter?

For example, if I have two cell arrays and a numerical matrix, in these forms:

g =

TT

uID =

     3
     4
     5
    10

s =
    'CC'
    'NN'
    'AA'

I want to create 12 unique strings following these rules:

TT3CC
TT3NN
TT3AA
TT4CC
TT4NN
TT4AA
TT5CC
TT5NN
TT5AA
TT10CC
TT10NN
TT10AA

That can be used to label a table.

EDIT

Second set of naming rules:

TT3NN
TT4NN
TT5NN
TT10NN
TT3CC
TT4CC
TT5CC
TT10CC
TT3AA
TT4AA
TT5AA
TT10AA

1 Answer 1

1

Something like:

    g   = 'TT';
    uID = [3 4 5 6];
    s   = {'CC' 'NN' 'AA'};

    for i = 1:length(uID)
        for j = 1:length(s)
           names{(i-1)*length(s)+j} = strcat(g,int2str(uID(i)),s{j});
        end
    end

or

inc = 1;
for i = 1:length(uID)
    for j = 1:length(s)
       names{inc} = strcat(g,int2str(uID(i)),s{j});
       inc = inc + 1;
    end
end

?

You just have to transform all your variables into string.

to extract a string from a cell you can write: mycell{i}.

finally strcat concatenate the 3 parameters.

EDIT

For your second request it start to be a little bit more tricky:

sets    = {[1:numel(uID)],[1:numel(s)]};
[p1 p2] = ndgrid(sets{:});
comb    = sortrows([p1(:) p2(:)],2); 

for i = 1:length(comb)
     names{i} = strcat(g,int2str(uID(comb(i,1))),s{comb(i,2)});
end

I generate all the possible combination with ndgrid then i sort the combination array according to the second row.

you just need to change your s cell:

s = {'NN' 'CC' 'AA'}

Sign up to request clarification or add additional context in comments.

2 Comments

Please add an explanation what you're doing here as opposed to posting bare code.
Works very well thank you. Could this be easily altered to produce the second naming pattern shown in the OP?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.