MATLAB03: data type and file reading and writing

MATLAB03: data type and file reading and writing

The best way to learn a technology is to read the official documents. You can view the official documents of MATLAB

data type

The main data types in MATLAB are as follows:

The following describes the main data types in turn, MATLAB official document Describes all data types

Numeric type

In MATLAB, the variable of numerical type is double by default, and can be converted to other numerical types by type conversion

n = 3;
class(n)	% obtain double

n = int8(3);
class(n)	% obtain int8

The numerical types supported by MATLAB are shown in the following table:

value typedescribe
doubleDouble precision floating point number
singleSingle-precision floating-point
int88-bit signed integer
int1616 bit signed integer
int3232-bit signed integer
int6464 bit signed integer
uint88-bit unsigned integer
uint1616 bit unsigned integer
uint3232-bit unsigned integer
uint6464 bit unsigned integer

String type (char)

In MATLAB, the string type is defined by a pair of single quotation marks' wrapping a text Standard ASCII characters can be converted to corresponding ASCII codes

s1 = 'h';
uint16(s1)	% Get 104

Strings are stored in memory in the form of character matrix, which can be indexed and assigned:

str1 = 'hello';
str2 = 'world';

str3 = [str1 str2];
size(str3)		% obtain [1 10]

str4 = [str1; str2];
size(str4)		% obtain [2 5]
str = 'aardvark';
'a' == str				% obtain [1 1 0 0 0 1 0 0] Perform equivalent operation at each position
str(str == 'a') = 'Z'	% obtain 'ZZrdvZrk' it turns out to be the case that a All become Z

Structure

In MATLAB, structure is a data structure that stores {key: value}, which is similar to the dictionary in Python language

Basic use of structure

  • Similar to most programming languages, MATLAB uses To access fields in the structure:
%% Create structural questions
student.name = 'John Doe';
student.id = 'jdo2@sfu.ca';
student.number = 301073268;
student.grade = [100, 75, 73; ...
                 95, 91, 85.5; ...
                 100, 98, 72];
% Direct input student View structure
student
% Direct input student.grade View details
student.grade

%% filenames(student) Structure names can be listed (specific table below)
>>filenames(student)
ans =

  4×1 cell array
    {'name'  }
    {'id'    }
    {'number'}
    {'grade' }
  • Using subscript expressions on the structure list can expand or reduce the structure list
student(2).name = 'Ann Lane';
student(2).id = 'aln4@sfu.ca';
student(2).number = 301078853;
student(2).grade = [95 100 90; 95 82 97; 100 85 100];
student

student(1) = []		% delete student First item in the list
  • Structures can be cascaded, that is, the value of fields in structures can also be structures:
A = struct('data', [3 4 7; 8 0 1], ...
	'nest', struct('testnum', 'Test 1', ...
        'xdata', [4 2 8], ...
        'ydata', [7 1 6]));
A(2).data = [9 3 2; 7 6 5];
A(2).nest.testnum = 'Test 2';
A(2).nest.xdata = [3 4 2];
A(2).nest.ydata = [5 0 9];

Common functions of structures

Function function

functioneffect
structCreate structure
struct2cellConvert structure to cell array
cell2structConvert a cell array to a structure
isstructJudge whether a variable is a structure
structfunApply a function to each field of the structure
fieldnamesGets all field names of the structure
isfieldDetermine whether the structure contains a field
getfieldGets the value of a field in the structure
setfieldAssign a value to a field in the structure
rmfieldDelete a field in a structure
orderfieldsSort structure fields
###1.4 cell array in MATLAB, cell array is a data structure that can accommodate different types of elements, similar to the list in Python language

1.4.1 basic use of cell array

We can use {} to define a cell array like a matrix:

A = { [1 4 3; 0 5 8; 7 2 9]		'Anne Smith' ;...
3+7i		-pi:pi:pi}
A(1,1)={[1 4 3; 0 5 8; 7 2 9]};
A(1,2)={'Anne Smith'};
A(2,1)={3+7i};
A(2,2)={-pi:pi:pi};
A
A{1,1}=[1 4 3; 0 5 8; 7 2 9];
A{1,2}='Anne Smith';
A{2,1}=3+7i;
A{2,2}=-pi:pi:pi;
A

The above three methods are equivalent, in which the second method uses unit index assignment and the third method uses content index assignment

  • There are two ways to access data in a cell array: the cell index () and the content index {}

Because the subset of cell array is still cell array, in the use of indexer content, it is necessary to indicate whether we want to access a sub cell array or the content in the corresponding area of cell array

  • Using the cell index (), we get an array of sub cells
  • Using the content index {}, we get the content in the corresponding area of the cell array
    For the difference between unit index and content index, please refer to the official documents

Common functions of cell array

Function function

functioneffect
cellCreate a cell array
iscellDetermine whether a variable is a cell array
cell2matConvert cell array to matrix
cell2structConvert cell array to structure
mat2cellConverts an array to a cell array of the specified size
num2cellConverts an array to a cell array of the same size
struct2cellConvert structure to cell array
celldispRecursively displays the contents of a cell array
cellplotDraw the structure of cell array in image form
cellfunApply a function to each cell of the cell array
The 'mat2cell' function can specify the size of each cell of the cell array during conversion
a = magic(3)

b = num2cell(a)
% obtain
% [8] [1] [6]
% [3] [5] [7]
% [4] [9] [2]

c = mat2cell(a, [1 2], [2, 1])
% obtain
% [1x2 double] [6]
% [2x2 double] [2x1 double]

High dimensional cell array

A three-dimensional cell array can have three dimensions: row, column and layer When indexing cellular arrays, the order of priority from high to low is: row → column → layer

Using cat function, you can splice the cell array on the specified dimension

Function for judging variable data type

The following functions can judge the variable type:

Function function

functioneffect
isintegerJudge whether the input parameter is an integer array
islogicalJudge whether the input parameter is a logical quantity array
isnumericJudge whether the input parameter is a numeric array
isrealDetermine whether the input parameter is a real array
ischarJudge whether the input parameter is a character array
iscellJudge whether the input parameter is a cell array
isfloatDetermine whether the input array is a floating-point array
ishandleDetermines whether the input array is a valid graphic handle
isemptyDetermine whether the input array is empty
isprimeDetermines which array elements are prime
isnanDetermines which array elements are NaN
isinfDetermines which array elements are Inf
isequalDetermine whether the arrays are equal
##File reading and writing MATLAB supports the following file types:

File content extension function to read file function to write file

File contentExtensionFunctions to read filesFunction to write to file
MATLAB data*.matloadsave
Excel table*.xls,*.xlsxxlsreadxlswrite
Space delimited numbers*.txtloadsave
###Read and write data in MATLAB format. The data in MATLAB workspace can be expressed in ` * The mat ` format is saved in a file Use the save function to save the data to the file, and use the load function to read the data from the file
  • The syntax of the save function is as follows:
    • save(filename,variables) saves the variables into a file in binary form
  • save(filename,variables, '- ascii') saves the variables to a file as text
  • The syntax of the load function is as follows:
    • load(filename) reads data from a binary file
    • load(filename, '- ascii') reads data from a text file

The parameters filename and variables are in string format. If the variables parameter is not specified, all variables in the current workspace will be stored in the file

Complex data formats, such as struct and cell, do not support storage in binary format

Reading and writing Excel tables

Excel data can be read and written using xlsread and xlswrite functions. The syntax is as follows:

  • Syntax for reading Excel files: [num,txt,raw] = xlsread(filename,sheet,xlRange)
Score = xlsread('04Score.xlsx')
Score = xlsread('04Score.xlsx', 'B2:D4')
[Score Header] = xlsread('04Score.xlsx')

Syntax for writing Excel: xlswrite(filename,A,sheet,xlRange)

M = mean(Score)';
xlswrite('04Score.xlsx', M, 1, 'E2:E4');
xlswrite('04Score.xlsx', {'Mean'}, 1, 'E1');

Keywords: MATLAB

Added by cheikhbouchihda on Sat, 22 Jan 2022 06:26:42 +0200