Matlab —— 档案与变量存取

档案与变量存取

  • Variables : string, structure, cell
  • Data access

Variable (Data) Type Conversion

double()Convert to double precision
single()Conver to single precision
int8()Convert to 8-bit signed integer
int16()Convert to 16-bit signed integer
int32()Convert to 32-bit signed integer
int64()Convert to 64-bit signed integer
uint8()Convert to 8-bit unsigned integer
uint16()Convert to 16-bit unsigned integer
uint32()Convert to 32-bit unsigned integer
uint64()Convert to 64-bit unsigned integer
>> A=20

A =

    20

>> int8(A)

ans =

   20

Character(char)

  • A character is represented in ASCII using a numeric code between 0 to 255
  • Create a character or a string by putting them into a pair of apostrophe:
>> s1 = 'h'
whos
uint16(s1)

s1 =

h

  Name      Size            Bytes  Class    Attributes

  s1        1x1                 2  char               


ans =

    104

>> s1 = 'hex' 

s1 =

hex

>> whos
  Name      Size            Bytes  Class     Attributes

  ans       1x1                 2  uint16              
  s1        1x3                 6  char                

String

  • An array collects characters:
s1 = 'Example';
s2 = 'String';
  • String concatenation
s3 = [s1 s2];
s4 = [s1; s2];

注意 s1与s2的维度不同
在s3后再加一个blank

>> s1 = 'Example';
s2 = 'String ';
s3 = [s1 s2];
s4 = [s1; s2];
>> s3

s3 =

ExampleString 

>> s4

s4 =

Example
String 

Logical Operations and Assignments

  • Many numerical and logical operators can be applied to strings
>> str = 'aardvark';
>> 'a' == str

ans =

     1     1     0     0     0     1     0     0

>> str(3)

ans =

r

>> str(str == 'a') = 'z'

str =

zzrdvzrk

Compare the entire string with another?

  • 实现字符串的倒序
s1 =

Example

>> flip(s1)

ans =

elpmaxE

Structure

  • A method of storing heterogrneous data
  • Structures contain arrays called fields
  • Student assignment grades:
.nameJohn Doe
.idjdo2@sfu.ca
.number301073268
.grade100 75 73 95 91 85.5 100 98 72
>> student.name = 'John Doe';
student.id = 'jdo2@sfu.ca';
student.number = 301073268;
student.grade = [100,75,73;...
    95,91,85.5;...
    100,98,72];
student

student = 

      name: 'John Doe'
        id: 'jdo2@sfu.ca'
    number: 301073268
     grade: [3x3 double]

>> student.grade

ans =

  100.0000   75.0000   73.0000
   95.0000   91.0000   85.5000
  100.0000   98.0000   72.0000

Adding Information to A Structure

  • student(2)
.nameAnn Lane
.idaln4@sfu.ca
.number301078853
.grade95 100 90 95 82 97 100 85 100
>> 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 = 

1x2 struct array with fields:

    name
    id
    number
    grade

>> student(1)

ans = 

      name: 'John Doe'
        id: 'jdo2@sfu.ca'
    number: 301073268
     grade: [3x3 double]

>> student(2)

ans = 

      name: 'Ann Lane'
        id: 'aln4@sfu.ca'
    number: 301078853
     grade: [3x3 double]


>> student(2).grade(3)

ans =

   100
Structure FunctionDescription
cell2structConvert cell array to structure array
fieldnamesField names of structure, or public fields of object
getfieldField of structure array
isfieldDetermine whether input is structure array field
isstructDetermine whether input is structure array
orderfieldsOrder fields of structure array
rmfieldRemove fields from structure
setfieldAssign values to structure array field
structCreate structure array
struct2cellConvert structure to cell array
structfunApply function to each field of scalar structure
% 部分函数用法及运行结果示例
>> fieldnames(student)

ans = 

    'name'
    'id'
    'number'
    'grade'

>> rmfield(student,'id')

ans = 

1x2 struct array with fields:

    name
    number
    grade

Nesting 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];
A.nest

ans = 

    testnum: 'Test 2'
      xdata: [3 4 2]


ans = 

    testnum: 'Test 1'
      xdata: [4 2 8]
      ydata: [7 1 6]


ans = 

    testnum: 'Test 2'
      xdata: [3 4 2]

Cell Array

  • Another method of storing heterogeneous data
  • Similar to matrix but each contains different type of data
  • Declared using { }
[ 1 4 3 ; 0 5 8 ; 7 2 9 ]‘Anne Smith’
3 + 7i[ -∏ 0 Π ]
%%
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
---------------------------------------------------------------------
>> 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 = 

          [3x3 double]    'Anne Smith'
    [3.0000 + 7.0000i]    [1x3 double]

Accessing Cell Array

  • Curly braces, { }, are used to access the “content” of cell arrays
>> A(1,1)

ans = 

    [3x3 double]

>> A{1,1}

ans =

     1     4     3
     0     5     8
     7     2     9

>> A{1,1}(6)

ans =

     2
Cell Array FunctionDescription
cellCreate cell array
cellmatConvert cell array to numeric array
cell2structConvert cell array to structure array
celldsipCell array content
cellfunApply function to each cell in cell array
cellplotGraphically display strcture of cell array
cellstrCreate cell array of strings from character array
iscellDetermine whether input is cell array
mat2cellConvert array to cell array with different sized cells
num2cellConvert array to cell array with consistently sized cells
struct2cellConvert structure to cell array

num2cell() & mat2cell()

  • Transform a matrix into a cell variable
>> a = magic(3)
b = num2cell(a)
c = mat2cell( a, [ 1 1 1], 3)  //参数说明:1.a matrix 2.row 3.column

a =

     8     1     6
     3     5     7
     4     9     2


b = 

    [8]    [1]    [6]
    [3]    [5]    [7]
    [4]    [9]    [2]


c = 

    [1x3 double]
    [1x3 double]
    [1x3 double]

Multidimensional Array

VecrotMatrixArray
rowrowsrows
columncolumnscolumns
layers

- 三维的array 第一个参数是row 第二个是column 第三个是layer

>> A{1,1,1} = [1 2;4 5];
A{1,2,1} = 'name';
A{2,1,1} = 2 - 4i;
A{2,2,1} = 7;
A{1,1,2} = 'Name2';
A{1,2,2} = 3;
A{2,1,2} = 0:1:3;
A{2,2,2} = [4 5]';
>> A

A(:,:,1) = 

          [2x2 double]    'name'
    [2.0000 - 4.0000i]    [   7]


A(:,:,2) = 

    'Name2'         [         3]
    [1x4 double]    [2x1 double]

cat()

  • Array Concatenation
>> A = [1 2;3 4];
B = [5 6;7 8];
C = cat(1,A,B);   % row
D = cat(2,A,B);   % column
E = cat(3,A,B);   % layer
>> C

C =

     1     2
     3     4
     5     6
     7     8

>> D

D =

     1     2     5     6
     3     4     7     8

>> E

E(:,:,1) =

     1     2
     3     4


E(:,:,2) =

     5     6
     7     8

利用cat(),A 和 B 建立 multidimensional array

>> A{1,1} = [1 2;4 5];
A{1,2} = 'Name';
A{2,1} = 2 - 4i;
A{2,2} = 7;
B{1,1} = 'Name2';
B{1,2} = 3;
B{2,1} = 0:1:3;
B{2,2} = [4 5]';
C = cat(3,A,B)

C(:,:,1) = 

          [2x2 double]    'Name'
    [2.0000 - 4.0000i]    [   7]


C(:,:,2) = 

    'Name2'         [         3]
    [1x4 double]    [2x1 double]

reshape() : (r1,c1)–>(r2,c2)

  • Return a new array with assigned rows and columns
>> A = {'James Bond',[1 2;3 4;5 6]; pi,magic(5)}   % A:2×2
C = reshape(A,1,4)    % C:1×4

A = 

    'James Bond'    [3x2 double]
    [    3.1416]    [5x5 double]


C = 

    'James Bond'    [3.1416]    [3x2 double]    [5x5 double]
  • Exercise : create a matrix B from the martix A below using reshape:
>> A = [1:3;4:6]

A =

     1     2     3
     4     5     6

>> B = reshape(A,3,2)

B =

     1     5
     4     3
     2     6

Checking Variable And Variable Status

isFunctionDescription
isintegerDetermine if input is integer array
islogicalDetermine if input is logical array
isnanDetect an element that isnot a number(NaN)
isnumericDetermine if input is numeric array
isprimeDetect prime elements of array
isrealDetermine if all array elements are real numbers
iscellDetermine if input is cell array
ischarDetermine if input is character arrar
inemptyDetermine if input is empty array
isequalDetermine if arrays are numerically equal
isfloatDetermine if input is floating-point array
isglobalDetermine if input is global variable
ishandleDetect valid graphics object handles
ininfDetermine infinite elements of array

File Access

  • File System <–> Work Space
  • Supported file formats:
File ContentExtensionDescriptionImport FunctionExport Function
MATLAB formatted dataMATSaved MATLAB workspaceloadsave
TextSpace delimited numbersloadsave
SpreadsheetXLS,XLSXEXCELxlsreadxlswrite

save() & load()

  • Save (all) workspace data to a file:
clear; a = magic(4);
save mydata1.mat            % 将 workspace 所有变量存储在 mydata1.mat
save mydata2.mat -ascii     % 可以用记事本打开,即可阅读,纯文本
  • Load data stored in a file:
load('mydata1.mat')
load('mydata2.mat','-ascii')

Save a specific variable:

save mydata1.mat x    % 只储存变量 x

Excel File Reading : xlsread()

  • Read from Excel spreadsheet
Score = xlsread('04Score.xlsx')
Score = xlsread('04Score.xlsx','B2:D4')

Excel File Writing : xlswrite()

  • Calculate the means and write into Excel spreadsheet
M = mean(Score')';     % ' 意为 转置
xlswrite('04Score.xlsx',M,1,'E2:E4');
xlswrite('04Score.xlsx',{'Mean'},1,'E1');

Getting Text in Excel Spreadsheet

  • Getting both the tet and numbers
[Score Header] = xlsread('04Score.xlsx')
% [numeric string] header 是用 cell 进行存储的

Low-level File Input/Output

  • Read and write file at the byte or character level
  • A file has an ID fid
  • Location in the a specifiedd by a pointer that can be moved around
FunctionDescripyion
fopenOpen file, or obtain information about open files
fcolseClose one or all open files
fscanfRead data from text file
fprintfWrite data to text file
feofTest for end-of-file

- Open and close a file:

fid = fopen('[filename]','[permission]');
status = fclose(fid);
  • Exsecise : write sine values into a file
x = 0:pi/10:pi ; 
y = sin(x);
fid = fopen('sinx.txt','w');
for i = 1:11
    fprintf(fid,'%5.3f %8.4f\n',x(i),y(i));
end
fclose(fid);
type sinx.txt

Read and Write through Formatted I/O

  • 几乎与C完全相同
  • %g 与 %f 表示浮点数
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值