![normal](/data/stemkbcom/level-normal.png)
Converting a cell array into a structure in Octave
In this lesson, I will explain how to convert a cell array into a structure using the cell2struct() function in Octave.
Let me give you a practical example.
Create an array of cells in the variable A.
>> A={"Math", "Latin", "Science"; 97, 60, 78};
This cell array is composed of a table with two rows and three columns.
Math | Latin | Science |
97 | 60 | 78 |
To convert it into a structure, use the function cell2struct()
Type B=cell2struct(A, {'exam', 'grade'})
>> B=cell2struct(A, {'exam', 'grade'})
The function has two parameters:
- The first parameter is the variable A, which contains the array of cells.
- The second parameter is the list of fields in the structure, enclosed in curly braces, i.e., {'lesson', 'grade'}.
A structure of array with the data from the cell array is created in the variable B.
For example, if you enter B(1,1,:)(:), you will obtain the data from the first column.
>> B(1,1,:)(:)
ans =
scalar structure containing the fields:
exam = Math
grade = 97
If you enter B(2,1,:)(:), you will obtain the data from the second column.
>> B(2,1,:)(:)
ans =
scalar structure containing the fields:
exam = Latin
grade = 60
If you enter B(3,1,:)(:), you will obtain the data from the third column.
>> B(3,1,:)(:)
ans =
scalar structure containing the fields:
exam = Science
grade = 78