Change type of a structure field

16 ビュー (過去 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 Center および File ExchangeJSON Format についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by