Change type of a structure field

조회 수: 14 (최근 30일)
Ben
Ben 2014년 5월 17일
댓글: dpb 2014년 5월 17일
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.

채택된 답변

dpb
dpb 2014년 5월 17일
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
Ben
Ben 2014년 5월 17일
Yup, that did it, thanks.
dpb
dpb 2014년 5월 17일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 JSON Format에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by