Change type of a structure field

19 views (last 30 days)
Ben
Ben on 17 May 2014
Commented: dpb on 17 May 2014
I'm fairly new to Matlab, so this might be a simple question or one that just isn't possible. I have a bunch of data that was grabbed from a JSON file. For one particular field, there might have been one or more words in the JSON object for any given item. The problem is that the toolbox I used (JSONlab) made that field a character array if there was only one word, and a cell array if there were more than one word. I would like all of the fields for each item to be cell array, regardless of the number of words in that field. Is there a way to force character arrays to become cell arrays?
Here's what I've tried so far (data is a 1x6000 cell array with 5556 valid items):
for i = 1:5556
item = data{1,i};
categories = item.categories;
if ischar(categories)
item.categories = cellstr(categories);
end
end
This doesn't have any compile/run-time issues, but it doesn't actually change anything. For example, if the only thing in categories is "Mexican", then it's still a character array afterwards.

Accepted Answer

dpb
dpb on 17 May 2014
Does this help?
>> data{1}={'this is stuff'};
>> data{2}='word'
data =
{1x1 cell} 'word'
>> iscell(data{2})
ans =
0
>> iscell(data{1})
ans =
1
>> data(2)={data(2)}
data =
{1x1 cell} {1x1 cell}
>>
?
  2 Comments
Ben
Ben on 17 May 2014
Yup, that did it, thanks.
dpb
dpb on 17 May 2014
BTW, note the following for the above initial data array--
>> isnt=~cellfun(@iscell,data);
>> data(isnt)={data(isnt)}
data =
{1x1 cell} {1x1 cell}
May make your job a little simpler.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!