MATLAB Answers

Converting irregular nested python list to matlab array

2 views (last 30 days)
I am trying to convert an irregular python list ( by irregular I mean size of elements within each sub-list may not be same) to matlab array. The structure of the list is as follows :-
%Python list
nested_list = [
[
[[1,1], [2,2]],
[[3,3], [4,4], [5,5]]]
],
[
[[1,1], [2,2]],
[[3,3], [4,4], [5,5]]],
[[6,6]]
]
]
As you can see the array is 4D and size of each sub list is not constant. I don't wish to use scipy.io.savemat function. I have tried matlab's cell function but coudn't find a way to call it recursively. Is there a way to convert this list to a matlab array/cell array?
Thank You.

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 21 Jul 2021
Wouldn't that become a 3-D cell-array of 1-by-2 arrays? Maybe something like this:
nested_list{1,1,1} = [1,1];
nested_list{1,1,2} = [2,2];
nested_list{1,2,1} = [3,3];
nested_list{1,2,2} = [4,4];
nested_list{1,2,3} = [5,5];
nested_list{2,1,1} = [1,1];
nested_list{2,1,2} = [2,2];
nested_list{2,2,1} = [3,3];
nested_list{2,2,2} = [4,4];
nested_list{2,2,3} = [5,5];
nested_list{3,2,3} = [6,6];
This would be very clean to index into after checking the nonemptiness of the cell-elements.
Or do you want a cell-array of cell-arrays of cell-arrays?
%Python list
row11 = {[1,1],[2,2]};
row12 = {[3,3], [4,4], [5,5]};
layer1 = {row11,row12};
row21 = {[1,1],[2,2]};
row22 = {[3,3], [4,4], [5,5]};
row22 = {[6,6]};
layer2 = {row21,row22};
nested_list = {layer1,layer2};
This becomes a mess to index into:
nested_list{1}{2}{3} % etc...
Then you'll have to check the type of each cell-element along the way, I'd try to avoid that hassle and try to stick with the first data-structure - since cell-elements can be whatever types you need I don't easily see the benefits of having cell-arrays nested too deep.
HTH
  2 Comments
Bjorn Gustavsson
Bjorn Gustavsson on 21 Jul 2021
My python-skills are "very limited". The first naive approach would be to build a one-D list with elements of this type (possibly in python?):
[id1, id2, id2, cell_content_vector]
While at the same time keeping track of the largest indices in each dimension. After generating that it should be rather straightforward to loop through that array:
testCell = cell(max_id1,max_id2,max_id3);
for i0 = 1:numel(intermediate_cellarray,1)
i1 = intermediate_cellarray(i0,1);
i2 = intermediate_cellarray(i0,2);
i3 = intermediate_cellarray(i0,3);
vec = intermediate_cellarray(i0,4:end);
final_3D_cell{i1,i3,i3} = vec;
end

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!