MATLAB: Possibilities to read out cell arrays and properties efficiently

cell arraysMATLAB

Hi community,
I have a small question and it would be really nice, if you could help me.
Is there any efficient way to read out the porperties of objets, which are stored in a cell array? I have a nested code, where objects of a self-made class are stored in a large cell array, but I think the following short example shows the problem.
cellArray = cell(2,1);
obj1 = struct('A', 1, 'B', [1 2]);
obj2 = struct('A', 2, 'B', [3 4; 5 6]);
cellArray{1,1} = obj1;
cellArray{2,1} = obj2;
Now I am searchching for a solution to read out the values of 'B' efficiently. The following code won't work, just to give you an idea, what I mean:
MatrixB = cellArray{:,:}.B
My solution at the moment is not very elegant.
[row, column] = size(cellArray);
MatrixB = [];
for i = 1:row
for j = 1:column
MatrixB = [MatrixB; cellArray{i,j}.B];
end
end
If there is no way to avoid the for-loops, should I count the number of rows with another loop at first and preallocate the Matix?
Thanks for your help! Best regards, lukn13

Best Answer

If the objects are structures, then the most efficient way is to store your data in a non-scalar structure, then accessing the field data is really easy:
>> obj(1) = struct('A', 1, 'B', [1 2]);
>> obj(2) = struct('A', 2, 'B', [3 4; 5 6]);
>> obj.B
ans =
1 2
ans =
3 4
5 6
>> vertcat(obj.B)
ans =
1 2
3 4
5 6
>> obj(2).B
ans =
3 4
5 6
Note that you can create a non-scalar structure with just one struct call:
>> obj = struct('A', {1,2}, 'B', {[1 2],[3,4;5,6]});
If the objects are not structures, then most likely you will have to use a loop. You can always wrap it up with cellfun, or write your own mex function.