matlab programming day(2)table, cell and structure array

1. table

1.1 table

%endTime = [];
spendTime = randi([10,50],[10,1]);
id = [1:1:10]';
%在第几个cpu位置
cpuStation = zeros(10,1);
%在Stack的第几个位置,由低往高数
stackStation = zeros(10,1);
node = table(id,startTime,spendTime,cpuStation,stackStation)

1.2 Add columns to table

  • Add specific data for a column and initialize it
node.age=[1:1:100]'

1.3 table2struct function

table2struct(T,'ToScalar',true)

2. Cell array cell

2.1 Reference

Cell array (cell) in Matlab

2.2 Assignment statement

node(1,1) = {
    
    23}

2.3

3. Structure

3.1 Basic operations of structures


%1.结构体数组,先创建一个基结构的实例
student = struct("name",'jack',"age",12,"address","xi");
%新增字段
student.sex="man";
%删除字段
student = rmfield(student,"sex");
name = getfield(student,"name");
student = setfield(student,"name","tom");
%创建同类型第二个结构体
student(2).name = "rose";
%查看改结构体实例
student(1)
%在实例基础上创建新的对象
student(2)
student(3) = student(2)
%查看结构体的字段数
fieldnames(node)
%查看结构体数组的长度
length(node);

3.2 Convert table to struct

table1 = table(id,startTime,spendTime,cpuStation,stackStation);
%添加变量:node.age=[1:1:100]'
[row,col] = size(table1);
node = table2struct(table1(1,:),'ToScalar',true)
for i = 2:row
    node(i) = table2struct(table1(i,:),'ToScalar',true);
end

3.3 Convert struct to node

table2 = struct2table(node);

4. Other commonly used

4.1 Determine the type of data

class(data)

4.2 Combining nonlinear programming and structures

% min F(X)
% s.t
% AX <= b
% AeqX = beq
% G(x) <= 0
% Ceq(X) = 0
% VLB <= X <= VUB
clear
clc
x0 = [-2 -2 -2 --2];  %初始值! 
Aeq = [1 1 1 1];
beq = [4];
VLB = [-2 -2 -2 -2];
VUB = [2 2 2 2];
b =3;
student = struct("name","jack","age",23);
%[x, fval] = fmincon(@fun3, x0, A, b, Aeq, beq, VLB, VUB)  %两种都可以,后者可以传递参数
[x,fval]=fmincon(@(x) fun3(x,student), x0,[],[], Aeq, beq, VLB, VUB)
function f = fun3(x,student)
f = x(1)+x(2)+x(3)-x(4)+student.age;
end

Guess you like

Origin blog.csdn.net/qq_42306803/article/details/127498875