Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to create a matlab structure as such ds=struct('name',{{'my_name_is'},{'matlab_thining_hair'}}) which stores as a 1x2 structure array with a field name. A call to ds.name generates the output:

ds.name
ans = 'my_name_is'
ans = 'matlab_thining_hair'

Please note the single quotes in the output. They are important. That said, I need to create the above mentioned structure using the following variable: X = [1x46 char] [1x47 char] i.e., 1x2 cell, which I believe is actually a cell array of strings. Among other things, I've tried the following:

Y = cell2struct(X, 'name', 1)'

which results in a 1x2 structure array with fields name, however a call to Y generates the output:

Y.name
ans = my_name_is
ans = matlab_thining_hair

Note that the single quotes in the output are missing, and albeit both Y and ds are 1x2 struct arrays with fields name, the field values are not formatted the same and the structures also vary in their bytes size. Essentially what I need is a struct with fields of cell arrays, where essentially each cell array consists of a unique char array. I am at a loss as how to format the field values as character arrays? Any help would be much appreciated.

share|improve this question

The discrepancy in your example is that each element of your original example ds.name is a cell containing a char (e.g. {'my name is'}), whereas each element of X is a char (e.g. 'my name is'). If you change the type of each element of X from a char to a cell containing a char then you should get the behaviour you are looking for.

This is shown in the example below.

X2={{'my_name_is'},{'matlab_thinning_hair'}};

Y = cell2struct(X2, 'name', 1);

Y.name

ans =

'my_name_is'

ans =

'matlab_thinning_hair'

You could achieve this for your variable X by indexing through the elements and carrying out:

X2{1}={X{1}};

X2{2}={X{2}}

The matlab help here is quite helpful on this topic.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .