2019-12-10, 20:41
|
#1
|
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
|
MATLAB中单元格和数组的串联和索引有何不同?
我对MATLAB中单元格和数组的用法有些困惑,并希望在几点上有所澄清。这是我的观察结果:
- 数组可以动态调整其自身的内存以允许动态数量的元素,而单元格似乎不以相同的方式起作用:
a=[]; a=[a 1]; b={}; b={b 1};
- 可以从单元格中检索几个元素,但是似乎不能从数组中检索它们:
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.
这些正确吗?单元和阵列之间还有哪些其他不同用法?
回答:
单元格数组可能会有些棘手,因为您可以通过各种方式使用[] , () 和 {}语法来 创建 , 连接和 索引它们,尽管它们各自执行不同的操作。解决您的两点:
- 要生长单元阵列,可以使用以下语法之一:
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 ()
- 当您使用()索引单元格数组时,它返回单元格数组中单元格的子集。当您使用{}索引单元格数组时,它将返回以逗号分隔的单元格内容列表 。例如:
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' 。
更多&回答...
|
|
|