Matlab中元胞数组与结构体数组

目录

元胞数组与结构体数组

结构体数组

元胞数组

其他容器数组


元胞数组与结构体数组

        该示例比较元胞和结构体数组,并说明如何在每种类型的数组中存储数据。使用元胞和结构体数组都可以存储不同类型和大小的数据。

结构体数组

        结构体数组中数据包含在可按名称访问的字段中。例如,将运动员记录存储在一个结构体数组中。

sportsman(1).name = 'John Doe';
sportsman(1).times = 1.10;
sportsman(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];

sportsman(2).name = 'Ann Lane';
sportsman(2).times = 2.10;
sportsman(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];

sportsman


sportsman=1×2 struct
    name
    times
    test

        为每位运动者的测试结果创建一个条形图。

numsportsmans = numel(sportsman);
for p = 1:numsportsmans
   figure
   bar(sportsman(p).test)
   title(sportsman(p).name)
   xlabel('Test')
   ylabel('Result')
end

                                          

                                         

元胞数组

        元胞数组中数据包含在可按数值索引访问的元胞中。元胞数组的常见应用包括存储单独的文本段,以及存储电子表格中的异类数据。

        例如,在一个元胞数组中存储一段时间中三个城市的温度数据。

temperature(1,:) = {'2009-12-31', [45, 49, 0]};
temperature(2,:) = {'2010-04-03', [54, 68, 21]};
temperature(3,:) = {'2010-06-20', [72, 85, 53]};
temperature(4,:) = {'2010-09-15', [63, 81, 56]};
temperature(5,:) = {'2010-12-09', [38, 54, 18]};

temperature



temperature=5×2 cell
    {'2009-12-31'}    {1x3 double}
    {'2010-04-03'}    {1x3 double}
    {'2010-06-20'}    {1x3 double}
    {'2010-09-15'}    {1x3 double}
    {'2010-12-09'}    {1x3 double}

        按日期绘制每个城市的温度。

allTemps = cell2mat(temperature(:,2));
dates = datetime(temperature(:,1));

plot(dates,allTemps)
title('Temperature Trends for Different Locations')
xlabel('Date')
ylabel('Degrees (Fahrenheit)')

                                           

其他容器数组

        结构体和元胞数组是存储异类数据的最常用容器。可以方便地使用表来存储异构的列向数据或表格数据。或者,使用映射容器或创建自己的类。

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值