Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - matlab why data type conversion
matlab why data type conversion

There are 15 basic data types in Matlab, mainly integers, floating point, logic, characters, dates and times, structure arrays, cell arrays, function handles, etc.

1. Integer type: (int8; uint8; int16; uint16; int32; uint32; int64; uint64) Return the maximum and minimum value of this type of integer through the intmax(class) and intmin(class) functions Value, for example intmax('int8')=127;

2. Floating point: (single; double)

Floating point number: REALMAX('double') and REALMAX('single ') returns the maximum value of double-precision floating point and single-precision floating point respectively. REALMIN('double') and REALMIN ('single') return the minimum value of double-precision floating point and single-precision floating point respectively.

3. Logic: (logical)

Logical: The following example is the application of logical index in matrix operation. Elements greater than 0.5 in the 5*5 matrix are set to 0:

A = rand(5);

A(A>0.5)=0;

4. Character: (char)

Input characters in Matlab need to use single quotes. Strings are stored as character arrays, with each element occupying an ASCII character. For example, date characters: DateString=’9/16/2001’

It is actually a vector with 1 row and 9 columns. The row strings that make up a matrix or vector must be of the same length. You can use the char function to construct a character array and the strcat function to concatenate characters.

For example, the command name =, that is, the string 'abc'

What actually exists is 'abc'. At this time, if you need to extract a certain character element in the matrix, you need to use deblank The function removes spaces such as name

=char('abc','abcd'); deblank(name(1,:)).

In addition, Matlab also provides a more flexible cell array method. You can use the function cellstr to convert a string array into a cell array:

data= char('abc' ,'abcd')

length(data(1,:)) ->? 4

cdata=cellstr(data)

length(cdata{1 }) ->?3

Commonly used character manipulation functions

blanks(n) returns n null characters

deblank(s) removes the end of the string Contains null characters

(string) Execute the string as a command

findstr(s1,s2) Search the string

ischar(s) Determine whether it is a character String

isletter(s) determines whether it is a letter

lower(s) converts to lowercase

upper(s) converts to uppercase

strcmp( s1,s2) Compare whether the strings are the same

strncmp(s1,s2,n) Compare whether the first n characters in the string are the same

strrep(s1,s2,s3) Replace character s2 in s1 with s3

5. Date and time

Matlab provides three date formats: date string such as '1996-10-02', date sequence number Such as 729300 (January 1, 0000 is 1) and date vector such as 1996 10 2 0 0 0, followed by year, month, day, hour, minute and second.

Commonly used date operation functions

datestr(d,f) converts date numbers into strings

datenum(str,f) converts strings into Date number

datevec(str) date string conversion vector

weekday(d) calculates the number of weeks

eomday(yr,mth) calculates the last day of the specified month

calendar(str) returns calendar matrix

clock date vector of current date and time

date current date string

now current Serial numbers of dates and times

6. Structures

A structure is an array containing named "data containers" or fields. Fields in the structure can contain any data.

7. Construct a structure array

(1) Assignment method

The following assignment command generates a structure array named patient, which contains three fields. :

patient.name = 'John Doe';

patient.billing = 127.00;

patient.test = [79 75 73; 180 178 177.5; 220 210 205];

Enter patient in the command area to view the structure information:

name: 'John Doe'

billing: 127

test: [3x3 double]

Continuing assignment can expand the structure array:

patient(2).name = 'Ann Lane';

patient(2).billing = 28.50;

patient(2).test = [68 70 68; 118 118 119; 172 170 169];

After assignment, the structure array becomes [1 2].

(2) Construct a structure array: struct function

The basic form of the function is: strArray = struct('field1',val1,'field2',val2, ...)

For example:

weather(1) = struct('temp', 72,'rainfall', 0.0);

weather(2) = struct('temp ', 71,'rainfall', 0.1);

weather = repmat(struct('temp', 72, 'rainfall', 0.0), 1, 3);

weather = struct('temp', {68, 80, 72}, 'rainfall', {0.2, 0.4, 0.0});

(3) Access structural data

All of the following It is a legal structure array access command:

mypatients = patient(1:2) Get substructure data

mypatients(1) Access structure data

patient( 2).name accesses specific fields in structured data

patient(3).test(2,2) accesses specific fields in structured data (the field is an array)

bills = [patient.billing] Access multiple structures

tests = {patient(1:2).test} Extract structure data and convert it into a cell array

Use dynamic names of structure fields

You can give structure field names and access data through structName.(expression_r_r_r).

For example, the field name is expression_r_r_r and the structure name is structName. To access the data in row 7, columns 1 to 25, you can use the command: structName.

(expression_r_r_r)(7,1:25).

For example, there is an array of student weekly score data structures, and its data is established in the following way:

testscores.wang.week(1:25) = ...

[95 89 76 82 79 92 94 92 89 81 75 93 ...

85 84 83 86 85 90 82 82 84 79 96 88 98];

testscores .chen.week(1:25) = ...

[87 80 91 84 99 87 93 87 97 87 82 89 ...

86 82 90 98 75 79 92 84 90 93 84 78 81];

That is, the structure is named testscores, and the fields are named after each student, respectively wang and chen. Each student contains an array of score structures named week.

Now calculate the average score given the structure name, student name and starting and ending weeks.

Enter edit avgscore.m in the command window, enter the following code and save the file:

function avg = avgscore(struct,student, first, last)

avg = sum(struct.(student).week(first:last))/(last - first + 1);

Enter in the naming window: avgscore(testscores, 'chen', 7, 22) Calculate student Chen’s average score from week 7 to week 22.

(4) Add and delete structure fields

The command [struct](index).(field) can add or modify fields. For example, patient(2).ssn = '000-00-0000' adds a field named ssn to the patient structure.

To delete a field, use the rmfield function, such as patient2 = rmfield(patient, 'name') to delete the name field and generate a new structure.

8. Cell array: (cell)

Cell array provides a storage mechanism for different types of data and can store arrays of any type and latitude.

The rules for accessing cell arrays are the same as other arrays. The difference is that you need to use curly braces {} to access. For example, A{2,5} accesses the cell in row 2 and column 5 in cell array A. .

(1) Constructing a cell array: assignment method

Use curly braces to mark a cell array directly, such as:

A(1,1) = {[1 4 3; 0 5 8; 7 2 9]};

A(1,2) = {'abcd'};

A(2,1) = {3+7i};

A(2,2) = {-pi:pi/10:pi};

The above command creates a 2*2 cell array A . Continue to add cell elements and use assignment directly, such as A(2,3)={5}. Note that curly brackets are required. The simplified method is to create a combination of curly braces (cell array) and square brackets (), such as C = {[1 2], [3 4]; [5 6], [7 8]};

< p>(2) Constructing a cell array: Function method

Cell function. For example:

B = cell(2, 3);

B(1,3) = {1:3};

(3) Access data

Data elements in the cell array can be accessed directly through indexes, for example:

N{1,1} = [1 2; 4 5];

N{1,2} = 'Name';

N{2,1} = 2-4i;

N{2,2} = 7;

c = N{1,2}

d = N{1,1}(2,2)

9. Function handle

Function A handle is a Matlab value or data type used to indirectly call a function. You can pass the function handle when calling other functions, or save the function handle in the data structure for later use. Function handles can be created through the command form fhandle = @functionname, such as trigFun=@sin, or anonymous function sqr = @(x) x.^2;.

The form of calling a function using a handle is fhandle(arg1, arg2, ..., argn) or fhandle() (no parameters). For example:

trigFun(1). Example:

function x = plotFHandle(fhandle, data)

plot(data, fhandle(data))

plotFHandle(@sin, -pi:0.01 :pi)

Data type conversion is similar to forced type conversion in C language e.g.:

y=9;

z=double(y);< /p>

Image data type conversion in Matlab

The data type of the image read in MATLAB is uint8, and the data type used in the matrix is ??double, so I2=im2double(I1)

: Convert image array I1 to double precision type; if not converted, overflow will occur when adding and subtracting uint8, and the error that may be prompted is: Function '*' is

not defined for values ??of class 'uint8'.

Image data type conversion function

By default, matlab stores the data in the image as double type, that is, 64-bit floating point number; matlab also supports unsigned integer types (uint8 and uint16); The advantage of uint type is that it saves space, and it needs to be converted to double type when operations are involved.

im2double(): Convert the image array to double precision type

im2uint8(): Convert the image array to unit8 type

im2uint16(): Convert the image Convert array to unit16 type