
How to Convert from Structure Array to Cell Array in Matlab
In this lesson, I'm going to show you how to convert a structure into a cell array in Matlab using the handy dandy function struct2cell().
It's quite a nifty tool that will make your life a lot easier when dealing with large data sets. So, let's get started!
Let's take a practical example.
Create a structure array like the following.
C = struct('course',{'Math', 'Latin', 'Science'},'students',{27,30,18})
This is a structure array composed of two fields ("course" and "students") with
course | students |
---|---|
Math | 27 |
Latin | 30 |
Science | 18 |
To convert the structure into a cell array, use the function struct2cell() by indicating the name of the structure within the parentheses.
Type D=struct2cell(C)
>> D=struct2cell(C);
Matlab creates a cell array with the data from the structure and saves it in the variable D.
For example, type D(1,1,:)(:) to display the data on the first row of the cell array.
>> D(1,1,:)(:)
ans =
{
[1,1] = Math
[2,1] = Latin
[3,1] = Science
}
Then type D(2,1,:)(:) to display the data on the second row of the cell array.
>> D(2,1,:)(:)
ans =
{
[1,1] = 27
[2,1] = 30
[3,1] = 18
}
This is quite a nifty little trick that one can employ in Matlab to convert a structure into a cell array.
It's a clever little technique that can save you quite a bit of time and hassle.