How to open a Nested Cell Array, when cells have parent-child relation in MATLAB

Hello, I have a nested structure.Think of a cell array. Each member is a "set".
Each set has "data" and "child" and "parent". Btw, a set can have another "set array" in it. In that case, when you open that "set array", you reach data, parent, child etc from the members of that array. Also, a set generally has multiple parents and children.
I am trying to reach from one cell to its original parent at the beginning. How do I do that? With loops it takes forever. Any help is appreciated. Thank you!
I guess the question can be put like that: Is there a way of not having this loop?
function p=getParent(prnt)
parents=[];
for s=1:size(prnt,2)
parents=[parents prnt(1,s).parents(1,:)];
end
p=parents;
end

1 Comment

It would probably help if you give a simple example of the structure in practice.

Sign in to comment.

 Accepted Answer

This does the same as your code, and it will be much faster:
function p = getParent2(prnt)
p = [prnt(1,:).parents];
p = p(1,:);
end
Depending on the size of the structure, the size of its fields arrays, and the data that you need to retrieve you might even be able to get rid of the indexing as well.
Your code is slow because you didn't preallocate the array before the loop. You can start to learn how to write efficient MATLAB code by reading these:
Also MATLAB offers very neat and efficient ways of accessing data in non-scalar structures:

More Answers (0)

Categories

Asked:

on 30 Aug 2016

Edited:

on 30 Aug 2016

Community Treasure Hunt

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

Start Hunting!