
Converting a Cell Array to a Structure in Matlab
In this tutorial, I will explain how to convert a cell array to a structure using Matlab's cell2struct() function.
Let's go through a practical example.
Create a cell array in the variable A
>> A={"Math", "Latin", "Science"; 27, 30, 18};
In this case, the cell array is a rectangular table with two rows and three columns.
Math | Latin | Science |
27 | 30 | 18 |
To convert the cell array into a structure, use the cell2struct() function.
Type B=cell2struct(A, {'course', 'students'})
>>B=cell2struct(A, {'course', 'students'});
The function has two parameters:
- The first parameter of the function is the variable A containing the cell array.
- The second parameter is the list of fields you want to have in the structure. You need to write them in curly braces, for example {'course', 'students'}.
The cell2struct() function creates a structure of arrays containing the data from the cell array in the variable B.
For example, if you type B(1,1,:)(:), you will get the data from the first column of the structure.
>> B(1,1,:)(:)
ans =
struct with fields:
course = Math
students = 27
If you type B(2,1,:)(:), you will get the data from the second column of the structure.
>> B(2,1,:)(:)
ans =
struct with fields:
course = Latin
students = 30
Finally, if you type B(3,1,:)(:), you will get the data from the third column of the structure.
>> B(3,1,:)(:)
ans =
struct with fields:
course = Science
students = 18
Well, you see, it's quite simple really. With this method, one can effortlessly convert any cell array to a neatly structured format in Matlab.