Some basic data structures in Matlab
September 27, 2011 at 01:41 AM | categories: uncategorized | View Comments
Some basic data structures in Matlab
John Kitchin
There are a variety of needs for storing complicated data in solving engineering problems.
Contents
cell arrays
A cell array can store a variety of data types. A cell array is enclosed by curly brackets. Here, we might store the following data in a variable to describe the Antoine coefficients for benzene and the range they are relevant for [Tmin Tmax]
c = {'benzene' 6.9056 1211.0 220.79 [-16 104]}
c = 'benzene' [6.9056] [1211] [220.7900] [1x2 double]
To access the elements of a cell array use curly brackets for indexing.
c{1}
ans = benzene
you can also index the cell array, e.g. to get elements 2-4:
[A B C] = c{2:4}
A = 6.9056 B = 1211 C = 220.7900
If you want to extract all the contents to variable names that are easy to read, use this syntax:
[name A B C Trange] = c{:}
name = benzene A = 6.9056 B = 1211 C = 220.7900 Trange = -16 104
structures
a structure contains named fields that can contain a variety of data types. Structures are often used to set options
s = struct('name','benzene','A',6.9056,'B',1211.0')
s = name: 'benzene' A: 6.9056 B: 1211
And you can add fields like this:
s.C = 220.79 s.Trange = [-16 104]
s = name: 'benzene' A: 6.9056 B: 1211 C: 220.7900 s = name: 'benzene' A: 6.9056 B: 1211 C: 220.7900 Trange: [-16 104]
we can access the data in a struct by the field
s.name s.Trange
ans = benzene ans = -16 104
It is an error to access a non-existent field, so you can check if it exists like this.
if isfield(s,'field3') s.field3 else 'no field 3 found' end
ans = no field 3 found
Not sure what fields are in the struct? This might be the case for a struct returned by a Matlab function, e.g. by an ode solver or optimization algorithm.
fieldnames(s)
ans = 'name' 'A' 'B' 'C' 'Trange'
containers.Map
A container.Map is like a dictionary, with a key:value relationship. You can use complicated key strings including spaces. By default, all keys must be the same type, e.g. all strings.
cM = containers.Map(); cM('name') = 'benzene'; cM('A') = 6.9056; cM('B') = 1211.0; cM('C') = 220.79; cM('Trange') = [-16 104]; cM('key with spaces') = 'random thoughts';
and we can access the data in a map by key:
cM('name') cM('key with spaces')
ans = benzene ans = random thoughts
it is also an error access a non-existent key, so we can check if it exists like this.
if cM.isKey('tre') cM('tre') else 'no tre key found.' end
ans = no tre key found.
Summary
These are a few of the ways to store/organize data in matlab scripts/functions.
% categories: basic