Compose-2025: Cells and Structs in OML
- Create a cell.
- Modify element in a cell.
- Create a struct.
- Modify a struct.
- Convert a struct to cell.
- Convert a cell to struct.
Creating a Cell
-
From the Editor window, enter the following line in a
new OML script:
a = {[1,2;3,4],6-2i;'hello', [0,0,0]; false,{'I''m another cell'}}
This creates a cell where:a (1,1)
is the matrix [1,2;3,4]a (1,2)
is the complex number 6-2ia (2,1)
is the string 'hello'a (2,2)
is the vector [0,0,0]a(3,1)
isfalse
, which is a kind of Booleana(3,2)
is another cell which only contains one string element‘I’m another cell’
-
Click Run to view the output:
Modifying an Element in a Cell
-
To reference a particular element in a cell, use
a{x,y}
with a being the name of the cell andx
andy
being the row and column, respectively. If you want to modify the element ina{2,1}
add the following:a{2,1} = [5,6;7,8]
-
Click Run to see the following results:
In this case, we see that the element at [2,1] was changed from the string
'hello'
to the matrix [5,6;7,8].
Create a Struct
-
From the Editor window, enter the following into a new
OML script:
student.name = ‘Bob’; student.age = 16; student.id = 8051
or, you can use struct() to perform the same assignment:
student = struct(‘name’,’Bob’,’age’,16,’id’, 8051)
This creates a struct which has three fields: age, id and name. The corresponding values are
16
,8051
andBob
. -
Click Run to view the output in the OML Command window:
In the Variable Browser, you may expand this struct by clicking the plus sign,
+
, in front of student to check its field and the corresponding values:
Modify a Sruct
-
To add a new field called
score
in thestudent
struct, use the commands below:student.score = ‘A’
or
setfield(student,’score’,’A’)
Both return this result:
-
If you want to remove a field in an existing struct, you must use the function
rmfield. For example, to remove the
age
field in thestudent
struct, use the command below:rmfield(student,’age’)
This returns:
Convert a Struct to a Cell
struct2cell
. The original struct’s fields change to
the number index, as shown
below:student.name = 'Bob';
student.age = 18;
student.id = 8015
% transfer a struct to a cell
struct2cell(student)
This returns:
Convert a Cell to Struct
Cell = {'Bob','Lily','Emma';20,18,25;8051,8052,8053};
Fields = {'name','age','id'};
Struct = cell2struct(Cell,Fields)
This script converts a cell to a struct with the fields name, age, and id respectively:
Click +
in front of Struct in the Variable Browser to expand this struct. The Variable Browser displays this: