Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

Convert vector to cell array

Asked by Austin

Austin (view profile)

on 18 Jun 2013

I am trying to use this

xDataNumbers = [2.5 5 7 8 11.5]

as the datanames for a fints

tsobj = fints(dates, data, datanames)

so - the question is: How do I convert a vector with numbers into a "Cell array of data series names" in the form nn.n?

Thanks. A

3 Comments

Jan Simon

Jan Simon (view profile)

on 18 Jun 2013

It is not clear what this exactly means:

"Cell array of data series names" in the form nn.n
Austin

Austin (view profile)

on 18 Jun 2013

I have an array

xDataNumbers = [3.5 7 9.2 11.5 ...]

that I want to use as datanames for the third parameter in

tsobj = fints(dates, data, datanames)

The format should have max width of 5 with 1 decimal place (%5.1f I think). Another issue is that the datanames cant start with a number, so it's ok to prepend something like 'S: '

Oh, wait, can the dataname strings even contain any numbers??

Matt Kindig

Matt Kindig (view profile)

on 18 Jun 2013

What is the desired output for datanames?

Austin

Austin (view profile)

1 Answer

Answer by Kye Taylor

Kye Taylor (view profile)

on 18 Jun 2013
Accepted answer

The third input to the fints function is a cell array of strings that can be valid MATLAB identifiers. That is, the strings cannot start with numbers and can only contain letters, numbers, and the underscore. As a workaround, you could do this

% convert numeric array to cell, and convert all contents to strings
dataNamesInput = cellfun(@num2str,num2cell(xDataNumbers(:)),'uniformoutput',false);
% make sure first letter is not numeric (it will be 'x')
dataNamesInput = cellfun(@(s)['x',s],dataNamesInput,'uniformoutput',false);
% remove periods and replace with underscores
dataNamesInput = regexprep(dataNamesInput,'\.','_');

and use dataNamesInput as the third input. Someone may suggest using the genvarnames function, but it will replace periods with '0x2'. You may prefer that. In any case, you'll still need the first line of code above that converts numeric array to cell of strings.

1 Comment

Jan Simon

Jan Simon (view profile)

on 19 Jun 2013

This:

dataNamesInput = cellfun(@(s)['x',s],dataNamesInput, 'uniformoutput',false);
dataNamesInput = regexprep(dataNamesInput,'\.','_');

can be done faster by:

dataNamesInput = strcat('x', dataNamesInput);
dataNamesInput = strrep('.', '_');
Kye Taylor

Kye Taylor (view profile)

Contact us