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, ie 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.
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.
If your MATLAB version is new enough (ie >= R2013b) you can use a table
for this:
A = table([1.5,3.2; 0,2.7; 0.8,2.8],[4; 5; 4],'VariableNames',{'name1','name2'});
As you can see, the result is easy to inspect (visually) and easy to access:
A.name1(3,2) % is 2.8000
If you are dead set on using cells then I'd start with cell2mat
and see if that helps out.
vals = cell2mat(B{2}) % returns the array vals=[0 2.7 5]
You could also simply use your data as normal matrix from the start:
B = [ 1.5, 3.2, 4; 0, 2.7, 5];
And then utilize column 3 as your keys if that was your intent (and they are numeric). If the keys are not guaranteed numeric then a struct could be useful.
edit: DVarga gives a more detailed and useful answer, I think.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.