MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   MATLAB中单元格和数组的串联和索引有何不同? (https://www.labfans.com/bbs/showthread.php?t=23332)

poster 2019-12-10 20:41

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

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.[/LIST]这些正确吗?单元和阵列之间还有哪些其他不同用法?



[B]回答:[/B]

[URL="https://www.mathworks.com/help/matlab/cell-arrays.html"]单元格数组[/URL]可能会有些棘手,因为您可以通过各种方式使用[] , () [I]和[/I] {}语法来[URL="https://www.mathworks.com/help/matlab/matlab_prog/create-a-cell-array.html"]创建[/URL] , [URL="https://www.mathworks.com/help/matlab/matlab_prog/combine-cell-arrays.html"]连接[/URL]和[URL="https://www.mathworks.com/help/matlab/matlab_prog/access-data-in-a-cell-array.html"]索引[/URL]它们,尽管它们各自执行不同的操作。解决您的两点:
[LIST=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 ()[*]当您使用()索引单元格数组时,它返回单元格数组中单元格的子集。当您使用{}索引单元格数组时,它将返回以[URL="https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html"]逗号分隔[/URL]的单元格内容[URL="https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html"]列表[/URL] 。例如:

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的内容作为[URL="https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html"]逗号分隔列表[/URL] ,然后使用[]将这些值收集到数字数组中。因此, b{2:4}等效于写b{2}, b{3}, b{4}或2, 3, 4 。

关于对[URL="https://www.mathworks.com/help/matlab/ref/legend.html"]legend[/URL]的调用,语法legend(a{1:2})等效于legend(a{1}, a{2})或legend('1', '2') 。因此, [I]两个[/I]参数(两个单独的字符)传递给legend 。语法legend(b(1:2))传递单个参数,该参数是1×2字符串'12' 。
[/LIST]
[url=https://stackoverflow.com/questions/2662964]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 05:01

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