Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 MATLAB中单元格和数组的串联和索引有何不同?

我对MATLAB中单元格和数组的用法有些困惑,并希望在几点上有所澄清。这是我的观察结果:
  1. 数组可以动态调整其自身的内存以允许动态数量的元素,而单元格似乎不以相同的方式起作用:

    a=[]; a=[a 1]; b={}; b={b 1};
  2. 可以从单元格中检索几个元素,但是似乎不能从数组中检索它们:

    a={'1' '2'}; figure; plot(...); hold on; plot(...); legend(a{1:2}); b=['1' '2']; figure; plot(...); hold on; plot(...); legend(b(1:2)); %# b(1:2) is an array, not its elements, so it is wrong with legend.
这些正确吗?单元和阵列之间还有哪些其他不同用法?



回答:

单元格数组可能会有些棘手,因为您可以通过各种方式使用[] , () {}语法来创建连接索引它们,尽管它们各自执行不同的操作。解决您的两点:
  1. 要生长单元阵列,可以使用以下语法之一:

    b = [b {1}]; % Make a cell with 1 in it, and append it to the existing % cell array b using [] b = {b{:} 1}; % Get the contents of the cell array as a comma-separated % list, then regroup them into a cell array along with a % new value 1 b{end+1} = 1; % Append a new cell to the end of b using {} b(end+1) = {1}; % Append a new cell to the end of b using ()
  2. 当您使用()索引单元格数组时,它返回单元格数组中单元格的子集。当您使用{}索引单元格数组时,它将返回以逗号分隔的单元格内容列表 。例如:

    b = {1 2 3 4 5}; % A 1-by-5 cell array c = b(2:4); % A 1-by-3 cell array, equivalent to {2 3 4} d = [b{2:4}]; % A 1-by-3 numeric array, equivalent to [2 3 4] 对于d , {}语法提取单元格2,3和4的内容作为逗号分隔列表 ,然后使用[]将这些值收集到数字数组中。因此, b{2:4}等效于写b{2}, b{3}, b{4}或2, 3, 4 。

    关于对legend的调用,语法legend(a{1:2})等效于legend(a{1}, a{2})或legend('1', '2') 。因此, 两个参数(两个单独的字符)传递给legend 。语法legend(b(1:2))传递单个参数,该参数是1×2字符串'12' 。

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 04:58


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.