B站台湾大学郭彦甫|MATLAB 学习笔记|04 变量与档案存取

MATLAB学习笔记(04 变量与档案存取)

1. string字符串

string连接的两种方式:

s1 = 'Example';
s2 = 'String';

s3=[s1 s2];		%此形式得到s1和s2串联
s4=[s1; s2]; %此形式本应得到s1和s2分列两行,但是需要s1和s2的长度一致,此处长度不一致故报错


>> Class_4
Error using vertcat
Dimensions of arrays being concatenated are not consistent.

Error in Class_4 (line 5)
s4=[s1; s2];
 
>> s3

s3 =

    'ExampleString'

2. 逻辑运算符和赋值

str = 'aardvark'; %将字符串赋值给str
'a' == str;  %此为逻辑运算符,判断str中的每个字符是否等于a,若等于a则为1,不等于a则为0

b= str == 'a';  %str == 'a'将会得到一条关于1和0的字符串
str(str == 'a') = 'Z'  %str()='Z'表示依据()中得到的关于1和0的字符串,将str字符串中等于a的字符赋值为Z

>> Class_4

str =

    'ZZrdvZrk'
>> b

b =

  1×8 logical array

   1   1   0   0   0   1   0   0

P8 exercise

问题:What if we want to compare the entire string with another?

tf= strcmp(s1,s2) %如果s1==s2,则返回 tf 为1,否则为 0。

s1='abcde';
s2='dcbae';
TF1= strcmp(s1,s2); %得到的结果为1/0

s3='ccc';
s4='ccc';
TF2=strcmp(s3,s4);

disp(TF1);
disp(TF2);

>> Class_4
   0

   1

P9 exercise

问题:Write a script that inverts any given string

s1='I like the letter E';
s2='E rettel eht ekil I';  %如何将s1转变为s2

观察得到s1和s2字符串中的字符顺序颠倒,可以对字符串进行数组操作。

s1='I like the letter E';
i=length(s1); %得到s1的长度
s2= s1([i:-1:1]); %把字符串当成数组
disp(s2);

>> Class_4
E rettel eht ekil I

3. 结构体 (Structure)

Struture结构可以存储异构数据,其中包含的阵列叫做 fields

P11 exercise

题目:Retrieve the 3rd grade for Ann Lane(第三个成绩是95 100 90中的90)

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(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];


x= student(2).grade(7);  %在矩阵中row1,colunm3的元素为Ann Lane的第三个成绩(90)
disp(x);

>> Class_4

student = 

  struct with fields:

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

    90


  • Structure Functions
    一些与结构体有关的函数
函数名 作用
cell2struct 将元胞数组转换为结构体数组
fieldnames 返回元胞数组中的字段名称
getfield 返回结构体数组字段的值
isfield Determine whether input is structure array field
isstruct Determinewhether input is structure array
orderfields Order fields of structure array
rmfield Remove fields from structure
setfield Assign values to structure array field
struct Create structure array
struct2cell Convert structure to cell array
structfun Apply function to each field of scalar structure
  • struct的嵌套结构
A =  struct('data', [3 4 7; 8 0 1], 'nest', ...
struct('testnum', 'Test 1', ... 
'xdata', [4 2 8],'ydata', [7 1 6]));  %struct的语法为:s = struct(field,value)

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  %A(1).nest得到的是第2行的结构体, A(2).nest得到的是第6-8行的结构体

>> Class_4

ans = 

  struct with fields:

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


ans = 

  struct with fields:

    testnum: 'Test 2'
      xdata: [3 4 2]
      ydata: [5 0 9]

4. 原胞数组 (Cell Array)

与Struct一样,可以存储异构数据,且结构与数组相似,每个元素包含不同的类型。
如要表示以下数组:

%%%方法一,{}放在=之后
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

%%


>> Class_4

A =

  2×2 cell array

    {3×3 double        }    {'Anne Smith'      }
    {[3.0000 + 7.0000i]}    {[-3.1416 0 3.1416]}


A =

  2×2 cell array

    {3×3 double        }    {'Anne Smith'      }
    {[3.0000 + 7.0000i]}    {[-3.1416 0 3.1416]}


P16 exercise

题目:Create a cell array B that has the following structure

直接使用原胞数组

A{1,1}='This is the first cell';

A{1,2}=[5+j*6 4+j*5];

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

A{2,2}=["Tim","Chris"];  %注意此处用双引号""表示字符串数组中的多个元素,单引号''表示只有一个元素

A

>> Class_4

A =

  2×2 cell array

    {'This is the first cell'}    {[5.0000 + 6.0000i … ]}
    {3×3 double              }    {["Tim"    "Chris"   ]}


  • 获得原胞数组的内容
A{1,1}='This is the first cell';
A{1,2}=[5+j*6 4+j*5];
A{2,1}=[1 2 3; 4 5 6; 7 8 9;];
A{2,2}=["Tim","Chris"];  

C=A{2,1};  %输出为内容
D=A(2,1);  %输出为指针
E=A{2,1}(2,1);  %输出为row2 colunm1的cell中的row2 column1的一个数4
disp(C);
disp(D);
disp(E);

>> Class_4
     1     2     3
     4     5     6
     7     8     9

    {3×3 double}

     4
  • num2cell() 和 mat2cell() 的应用
函数名 内容
mat2cell Convert array to cell array with different sized cells
num2cell Convert array to cell array with consistently sized cells
a= magic(3);
b= num2cell(a);  %将a中的每个数转换成单独的cell,此处得到3*3的cell矩阵
c= mat2cell(a,[1 1 1],3);  %[1 1 1]是指将3行分成三部分,3表示3列为一个部分,得到的是1*3的cell矩阵
a
b
c

>> Class_4

a =

     8     1     6
     3     5     7
     4     9     2


b =

  3×3 cell array

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


c =

  3×1 cell array

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

  • 矩阵的串接((cat() ))
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
D
E

>> Class_4

C =

     1     2
     3     4
     5     6
     7     8


D =

     1     2     5     6
     3     4     7     8


E(:,:,1) =

     1     2
     3     4


E(:,:,2) =

     5     6
     7     8


  • reshape() 函数
A = {'James Bond', [1 2;3 4;5 6]; pi, magic(5)} ;
A
C = reshape(A,1,4)  %将cell矩阵A重新排序,从2*2变为1*4,注意排序规则为按照矩阵元素顺序排序

>> Class_4

A =

  2×2 cell array

    {'James Bond'}    {3×2 double}
    {[    3.1416]}    {5×5 double}


C =

  1×4 cell array

    {'James Bond'}    {[3.1416]}    {3×2 double}    {5×5 double}



P23 exercise

题目:Create a matrix B from the matrix A below using reshape:

A=[123456]B=[154426]

A = [1:3; 4:6];
A
B=reshape(A,3,2);
B

>> Class_4

A =

     1     2     3
     4     5     6


B =

     1     5
     4     3
     2     6

5. File Access

  • save和load
save mydata1.mat  %按此形式存储,如果用记事本打开,为乱码内容
save mydata2.mat -ascii  %记事本打开可以看到数值内容

load('mydata1.mat')  %加载出来得到完整的文件
load('mydata2.mat','-ascii')  %加载出来变量名不见,相比mydata1.mat,实际得到的内容较少

  • wtite
M = mean(Score')';   % '号表示将Score转置(从列变成行)求平均再转置为列
xlswrite('04Score.xlsx', M, 1, 'E2:E4');   %M表示variable,1表示sheet,E2:E4表示位置
xlswrite('04Score.xlsx', {'Mean'}, 1, 'E1'); %写标头
  • 文件输入输出函数(相对重要的)
函数名 内容
fopen Open file, or obtain information about open files
fprintf Write data to text file
posted @   一抹微瀾  阅读(119)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示