matlabdata-structurescell-arraymatrix-indexingheterogeneous-array

How do I represent and access elements of this multivalued data structure?


I am trying to implement the Brooks-Iyengar algorithm for sensor fusion, and am trying to represent the following data structure in MATLAB.

A = {([1.5,3.2],4), ([0,2.7],5), ([0.8,2.8],4)}

I tried doing the following

B = {{[1.5,3.2],4},{[0,2.7],5}}

But then I don't know how to access each element, i.e. 1.5, 3.2 and the 4 as well as the next set of values. I get one set of elements from B{1}, but am not able to get the individual values after.

Any ideas or pointers to appropriate links would be helpful.


Solution

  • With the current structure, you can simply continue the indexing:

    >> B{1}
    
    ans = 
    
        [1x2 double]    [4]
    
    >> B{1}{1}
    
    ans =
    
        1.5000    3.2000
    
    >> B{1}{1}(2)
    
    ans =
    
        3.2000
    
    >> B{1}{2}
    
    ans =
    
         4
    

    To remove an item from the main structure you can use the following syntax B(1) = [];:

    >> B = {{[1.5,3.2],4},{[0,2.7],5}}
    
    B = 
    
        {1x2 cell}    {1x2 cell}
    
    >> B(1) = []
    
    B = 
    
        {1x2 cell}
    
    >> B{1}
    
    ans = 
    
        [1x2 double]    [5]
    
    >> 
    

    You could also choose to represent the data in a structure array (with some better property naming):

    >> s = struct('prop1',{4, 5},'prop2', {[1.5,3.2], [0,2.7]})
    
    s = 
    
    1x2 struct array with fields:
    
        prop1
        prop2
    
    >> s(1).prop1
    
    ans =
    
         4
    
    >> s(1).prop2
    
    ans =
    
        1.5000    3.2000
    
    >> s(1).prop2(2)
    
    ans =
    
        3.2000
    

    To remove an item, you can use the similar syntax:

    s(1) = []
    

    If you want to performs some operations on the data elements, you can also choose to go with the OOP approach, and create a class that represents a single data element and optionally one that represents the whole data set. Accessing the data members is natural.