Collapsing nested cell array values into simple numerical array
9 次查看(过去 30 天)
显示 更早的评论
I have used regexp to find some numbers in each element of a cell array. However, the result of the regexp is a nested cell array such as the following:
>> celldisp(a)
a{1}{1}{1} =
5
a{2}{1}{1} =
36
All I want is to have the result collapsed into the simple numerical array [5 36] but I have been unable to get the right syntax.I have tried things like the following but the nesting seems to cause issues:
>> b=[a{:}{1}{1}]
Expected one output from a curly brace or dot indexing expression, but there were 2 results.
>> b=cell2mat(a{:}{1}{1})
Expected one output from a curly brace or dot indexing expression, but there were 2 results.
>> b=cell2mat(a)
Error using cell2mat (line 52)
CELL2MAT does not support cell arrays containing cell arrays or objects.
I could certainly use a loop to iterate through it, but it seems like there should be some very simple syntax that does the trick.
0 个评论
采纳的回答
Stephen23
2019-12-4
编辑:Stephen23
2019-12-4
"I have used regexp to find some numbers in each element of a cell array."
If the regular expression only needs to match once, then use the 'once' option to remove one level of nesting.
"but it seems like there should be some very simple syntax that does the trick"
Not really: nesting data in container arrays makes it difficult to access.
>> C = [a{:}];
>> C = [C{:}];
>> V = [C{:}]
V =
5 36
Read these to know more:
3 个评论
Stephen23
2019-12-4
>> C = {'hello iter: 5 blah','world iter: 23 blah'};
>> D = regexp(C,'iter: (\d*)','tokens','once');
>> V = cellfun(@str2num,[D{:}]) % your code
V =
5 23
>> V = str2double([D{:}]) % no need for CELLFUN
V =
5 23
"Was there a way to do the initial regexp that would have gotten to the end result more cleanly?"
>> D = regexp(C,'(?<=iter: )\d*','match','once');
>> V = str2double(D)
V =
5 23
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!