如何串联和索引在MATLAB细胞和数组不同? [英] How do concatenation and indexing differ for cells and arrays in MATLAB?
问题描述
我有点困惑在MATLAB细胞和数组的使用,并愿谈几点澄清。这里是我的意见:
I am a little confused about the usage of cells and arrays in MATLAB and would like some clarification on a few points. Here are my observations:
-
的阵列可以动态地调整它自己的存储器,以允许元件的动态数,而细胞似乎不以同样的方式起作用:
An array can dynamically adjust its own memory to allow for a dynamic number of elements, while cells seem to not act in the same way:
a=[]; a=[a 1]; b={}; b={b 1};
若干元素可以从细胞中进行检索,但它似乎并不像他们可以从数组:
Several elements can be retrieved from cells, but it doesn't seem like they can be from arrays:
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.
这些是正确的?什么是细胞和阵列之间的一些其他不同的用途?
Are these correct? What are some other different usages between cells and array?
推荐答案
电池阵列可有点棘手,因为你可以使用 []
,()
,和的 {}
在的创建,串联和索引他们,虽然他们各自做不同的东西。解决您的两点:
Cell arrays can be a little tricky since you can use the []
, ()
, and {}
syntaxes in various ways for creating, concatenating, and indexing them, although they each do different things. Addressing your two points:
-
要长出一个单元阵列,可以使用以下语法之一:
To grow a cell array, you can use one of the following syntaxes:
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 ()
在索引单元阵列与()
,它返回细胞在一个单元阵列的一个子集。当指数随 {}
,它返回的逗号分隔的列表的单元格内容。例如:
When you index a cell array with ()
, it returns a subset of cells in a cell array. When you index a cell array with {}
, it returns a comma-separated list of the cell contents. For example:
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作为< A HREF =http://www.mathworks.com/help/techdoc/matlab_prog/br2js35-1.html相对=nofollow>逗号分隔的列表,然后使用 [ ]
来收集这些值转换为数值数组。因此, B {2:4}
等同于写 B {2},B {3},B {4}
或 2,3,4
。
For d
, the {}
syntax extracts the contents of cells 2, 3, and 4 as a comma-separated list, then uses []
to collect these values into a numeric array. Therefore, b{2:4}
is equivalent to writing b{2},b{3},b{4}
, or 2,3,4
.
对于您的来电 LEGEND ,语法传奇({1:2})
等同于传奇({1},A {2})
或传奇('1','2')
。这样的两个的参数(两个分开的字符)传递到传奇。语法传奇(二(1:2))
传递一个参数,它是一个1×2串 '12'
。
With respect to your call to LEGEND, the syntax legend(a{1:2})
is equivalent to legend(a{1},a{2})
, or legend('1','2')
. Thus two arguments (two separate characters) are passed to LEGEND. The syntax legend(b(1:2))
passes a single argument, which is a 1-by-2 string '12'
.
这篇关于如何串联和索引在MATLAB细胞和数组不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!