Tim*_*Tim 4 arrays indexing matlab concatenation cell
我对MATLAB中的单元格和数组的使用有点困惑,并希望对几点进行一些澄清.以下是我的观察:
数组可以动态调整自己的内存以允许动态数量的元素,而单元格似乎不会以相同的方式运行:
a=[]; a=[a 1]; b={}; b={b 1};
Run Code Online (Sandbox Code Playgroud)可以从单元格中检索多个元素,但它们似乎不是来自数组:
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.
Run Code Online (Sandbox Code Playgroud)这些是正确的吗?单元格和数组之间有什么其他不同的用法?
gno*_*ice 12
单元阵列可有点棘手,因为你可以使用[]
,()
,和 {}
语法在各种方式创建,串联和索引他们,虽然他们各自做不同的事情.解决你的两点:
要生成单元格数组,可以使用以下语法之一:
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 ()
Run Code Online (Sandbox Code Playgroud)使用索引单元格数组时()
,它将返回单元格数组中的单元格子集.使用索引单元格数组时{}
,它将返回以逗号分隔的单元格内容列表.例如:
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]
Run Code Online (Sandbox Code Playgroud)
对于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'
.