Summary of operations related to Matlab and C/C + + cell array cell

1 operation of cell array cell in MATLAB

Create a 6 * 4 array with reshape function:

A = reshape(1:20,5,4)'

be careful:
During the use of reshape function, it should be noted that the dimension of the created array should correspond to the original quantity, otherwise the following error will be reported:

1.1 mutual conversion of array and cell numbers: mat2cell, cell2mat

1.1.1 mat2cell usage form

  • C = mat2cell(A,dim1Dist,...,dimNDist) divides array a into smaller arrays and returns them in cell array C. The vector dim1Dist,... dimNDist specifies how to divide the rows, columns, and (if applicable) higher dimensions of A. smaller arrays in C can have different sizes. A can contain any data type.
  • C = mat2cell(A,rowDist) divides array A into an n × 1-cell array C, where n is equal to the number of elements in rowDist.

For example, if A is 60 × 50 array, you can specify this parameter as [10, 20, 30], [25, 25] to divide A, as shown in the following code and figure. C is A cell array, which contains six sub arrays split from A.

C = mat2cell(A,[10 20 30],[25 25])

Example 1: divide the array and return the sub array in the form of cell array

Divide A into four 2 × 3 subarray. Returns A subarray as A cell array.

C = mat2cell(A,[2 2],[3 3])

Use the celldip function to display the subarray in C.

celldisp(C)

Example 2: dividing arrays by rows

Divide the row of a so that the cell array contains two subarrays. Since the first element of rowDist is 2, the first cell of C contains the first row of A. The second element of rowDist is 3, so the next cell of C contains the next three rows of A. The sum of the elements of rowDist is equal to the number of rows of A.

rowDist = [1 3];
C = mat2cell(A,rowDist)


Also use the celldip function to display subarrays

celldisp(C)

1.1.2 cell2mat usage form

A = cell2mat(C) converts a cell array to a normal array. The elements of a cell array must all contain the same data type, and the resulting array must also be of that data type.

For example, the contents of cells in the same column must have the same number of columns, but do not need to have the same number of rows:

Example 1: convert cell array into numeric array

Converts a numeric array of six cells of a cell array into a numeric array.

C = {[1 7], [2 3 4],[12];
     [13 11 ; 12 23], [6 7 8; 10 11 12],[18;24]}

A = cell2mat(C)

Example 2: convert struct cell array into struct array

a.id = [12 3 8];
a.name = 'X';
b.id = [20 22 24];
b.name = 'h';
c = {a,b};
d = cell2mat(c)

c is a cell array

d is an array of structures

Example 3: convert cell array into struct array

n=3;
%% Initialize a cell array
c_info=cell(n,1);
id=[12 3 8];
 
name={'x','l','h'};
age=[20 22 24];
for i=1:n;
    c_info{i}.id=id(i);
    c_info{i}.name=name{i};
    c_info{i}.age=age(i);
end
%% Conversion code
cs_info=[c_info{:}]


cs_info is a structure array:

cs_ Value of info (1,1):

cs_ Value of info (1,2):

cs_ Value of info (1,3):

1.2 mutual conversion between cell array and table: cell2table, table2cell

1.2.1 cell2table usage form

  • T = cell2table(C) m × The contents of n-cell array C are converted to m × N table t. Each column of C provides the data contained in a variable of T.
  • T = cell2table(C,Name,Value) creates a table based on the cell array C with other options specified by one or more Name,Value for the group parameter.

Example: convert the cell array into a table according to the specified variable name

First, create a cell array C containing character vectors and numerical data:

C = {1 'matlab' 2 'A'; 2 'python' 3 'A+';...
    3 'C++' 4 'A++'; 5 'java' 6 'A-'}



Then convert the cell array C into a table according to the specified variable name.

T = cell2table(C,'VariableNames',{'id1' 'course' 'id2' 'grade'})

In particular, it should be noted that the conversion of cell arrays into tables can only be performed in Matlab version 2015 or above, and there is no cell2table function for those lower than 2013
The blogger's matlab is R2013a, so an error is reported in the application of cell2table:

This means that the function 'cell2table' is not defined as an input parameter of type 'cell'.

Normal operation results:

T=4×4 table
    id1    	  course         id2            grade
    ___    ____________    ________    ______________

     1     {'matlab' }        2           {'A'}    
     2     {'python'  }       3           {'A+'}    
     3     {'C++' }       	  4           {'A++'}    
     5     {'java'}           6           {'A-' }    

1.2.2 table2cell usage form

C = table2cell(T) converts table t to cell array C. Each variable in t becomes a cell column in C.

Example: convert table to cell array

Create a table T:

T = table(categorical({'M';'M';'F';'F';'F'}),[22;24;21;20;23],...
    [119 95;121 78; 125 86; 120 85; 122 90],...
    'VariableNames',{'Gender' 'Age' 'BloodPressure'},...
    'RowNames',{'Smith' 'Johnson' 'Williams' 'Jones' 'Brown'})

Converts T to a cell array.

C = table2cell(T)
C=5×3 cell array
    {[M]}    {[22]}    {1x2 double}
    {[M]}    {[24]}    {1x2 double}
    {[F]}    {[21]}    {1x2 double}
    {[F]}    {[20]}    {1x2 double}
    {[F]}    {[23]}    {1x2 double}

1.3 convert an array to a cell array of the same size: num2cell

1.3.1 num2cell usage form

  • C = num2cell(A) converts array A to cell array C by placing each element of A in A separate cell of C.
  • C = num2cell(A,dim) divides the content of A into individual cells in C, where dim specifies which dimension of A each cell contains. Dim can be A scalar or vector of dimensions.

When dim = 1,2, [1,2]:
num2cell(A,1) creates a 1 × 3-cell array C, where each cell contains 2 of A × Column 1.
num2cell(A,2) creates a 2 × 1 cell array C, where each cell contains 1 of A × Three lines.
Num2cell (a, [1, 2]) creates a 1 × 1 cell array C, where each cell contains the entire array of A.

Example: convert an array to a cell array

Use the magic function to create a value of 4 * 4:

a = magic(4)


Convert it to a cell array:

c = num2cell(a)

2 operation of cell array cell in C / C + + (for mat file)

Note that you need to load the header file before operating on the mat file: #include "mat.h"

2.1 correlation function

2.1. 1. Open mat file: matOpen

MATFile *matOpen(const char *filename,const char *mode)

The input mode has the following forms:

  • r: Open as read-only
  • u: Update mode, readable and writable, but if the data file to be opened does not exist, a new file will not be created
  • w: Open in write mode, only write is allowed. If the data file to be opened does not exist, a new file will be created

2.1. 2. Read variables from mat file: matGetVariable

mxArray * matGetVariable(MATFile * pMF, const char * name);

Read the variable named name and return a data array pointer

2.1. 3. Read data in cell: mxGetCell

C/C + + also has a cell operation function for mat data:

EXTERN_C mxArray *mxGetCell(const mxArray *pa, mwIndex i);

Input:

  • pa: pointer to mxArray type;
  • i: Label of element in cell; Priority by column.

Output:

  • Pointer to mxArray type.

2.1. 4. Get the data in the data array: mxGetData

void *mxGetData(const mxArray *pa );

Cast is required when returning.

2.1. 5 obtain the dimension of data array matrix: mxGetM, mxGetN

size_t mxGetM(const mxArray *pa);// Gets the number of rows of the matrix pa
size_t mxGetN(const mxArray *pa);//Gets the number of columns of the matrix pa

2.1. 6 create a data array as a double floating point matrix: mxCreateDoubleMatrix

mxArray *mxCreateDoubleMatrix(mwSize m, mwSize n, mxComplexity flag);

2.1. 7 store variables in data array: mxSetData

void mxSetData( mxArray *pa, void  *newdata );

2.1. 8 save the data array into the mat file: matPutVariable

int matPutVariable(MATFile * pMF, const char * name, const mxArray * pA);

0 is returned for successful storage, and non-0 is returned for error storage

2.2 basic processing steps

Variable definition and initialization

 	MATFile *pmat;		//Pointer to mat file
    const char **dir;	//Element name list
    const char *file;	//mat file name
    int         ndir;	//Number of elements (matrix, cell) in mat file
    mxArray *cell1;		//Pointer to the cell data to be read
    mxArray *mat1;		//A pointer to an element in a cell
    double *a;			//Pointer to the first data of an element in a cell

First open the mat file

pmatFile= matOpen("data.mat", "r");//Open the file and return a pointer to mat data
	if (pmatFile == NULL)
	{
		printf("open mat File failed!");
		return 0;
	}

Then read the matrix list in the mat file (return the names of the elements contained in the mat)

dir = (const char **)matGetDir(pmatFile, &ndir);
    if (dir == NULL)
    {
        printf("read mat File failed!");
        return 0;
    }   

Then, read the cell named dir[0] from the open mat file and return the pointer to the matrix

Note: the matrix in MATLAB is stored first by column

cell1 = matGetVariable(pmatFile,dir[0]);//Point to a cell with the name dir[0]

Then get the number of rows and columns of cells

int cellM = (int)mxGetM(cell1);//Gets the number of rows of cells
int cellN = (int)mxGetN(cell1);//Gets the number of columns in the cell

Finally, the data in the finite cell is read in sequence

 for(int count=0;count<cellM*cellM;count++)
    {
        mat1 = mxGetCell(cell1,count);//Column first, pointing to the count+1 element in the cell

        a = (double*)mxGetData(mat1);//Point to the first data in mat1

        M = (int)mxGetM(mat1);//Gets the number of rows for mat1
        N = (int)mxGetN(mat1);//Gets the number of columns for mat1

        printf("element%d The dimension of is:(%d,%d)\n",count,M,N);

        for (int i=0;i<M;i++)
        {
            for (int j=0;j<N;j++)
                printf("%f ",a[j*M+i]);
            printf("\n");
        }
    }

reference resources

  • https://ww2.mathworks.cn/help/matlab/ref/struct2cell.html
  • https://blog.csdn.net/jnulzl/article/details/49623121
  • https://blog.csdn.net/left_la/article/details/8206645

Why don't you start with a key three times to show your gratitude

Keywords: C C++ MATLAB

Added by slipperyfish on Sun, 26 Dec 2021 09:49:29 +0200