Structure + arrayfun Function, Cell + cellfun Function (MATLAB Data Types)

Oct. 01, 2022

MATLAB Data Types

学习一门编程语言,在最开始的时候一般都会学习这门语言的数据结构(Data structure),或者说是数据类型(Data types)。根据所要解决的问题选择一个比较合理的数据类型,可以使处理过程变得高效和简洁,因此数据结构的学习和使用是很重要的一个步骤,也是很容易忽视的一个部分。

MATLAB支持的基本数据类型可以在Data Types - MathWorks查到:

image-20221001203128671


Structures + arrayfun Function

Structures和arrayfun函数的使用可以快速地处理相同类型的问题,非常符合MATLAB本身向量化编程的特性。

例如,arrayfun - MathWorks官方文档中提供的一个绘图的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
clc, clear, close all
rng("default")

% Create a structure array in which each structure has two fields containing numeric arrays.
S(1).X = 5:5:100; S(1).Y = rand(1, 20);
S(2).X = 10:10:100; S(2).Y = rand(1, 10);
S(3).X = 20:20:100; S(3).Y = rand(1, 5);

% Plot the numeric arrays
figure
hold(gca, "on")
grid(gca, "on")
box(gca, "on")
p = arrayfun(@(a) plot(a.X, a.Y), S);
p(1).Marker = 'o';
p(2).Marker = '+';
p(3).Marker = 's';

image-20221001204024432


Cell + cellfun Function

同样地,上述问题也可以使用Cell和cellfun的组合进行解决:

1
2
3
4
5
6
7
8
9
10
11
12
13
clc, clear, close all

X = {5:5:100, 10:10:100, 20:20:100};
Y = {rand(1,20), rand(1,10), rand(1,5)};

figure
hold(gca, "on")
grid(gca, "on")
box(gca, "on")
p = cellfun(@plot, X, Y);
p(1).Marker = 'o';
p(2).Marker = '+';
p(3).Marker = 's';

image-20221001205111116


参考

[1] Data Types - MathWorks

[2] arrayfun - MathWorks

[3] cellfun - MathWorks.