[英]Removing elements from a cell array in MATLAB
I have a cell array as shown below: 我有一个单元格数组,如下所示:
a = {[1 2 3] [5 3 6] [9 1 3]};
Now I want to remove the 1s from every array in a
that contains 1
so that the output is as shown 现在我想从每一个阵列中删除1S在a
包含1
使得如图所示的输出
a = {[2 3] [5 3 6] [9 3]};
I know the indices of arrays in cell array 'a' which contain 1. This can be done using for
loop and a temporary variable, but this is taking a lot of time (I want to perform the operation on a cell array of size something like 1x100000. The one above is just for an example) 我知道单元格数组'a'中的数组的索引包含1.这可以使用for
循环和临时变量来完成,但这需要花费很多时间(我想对大小的单元格数组执行操作)像1x100000。上面的一个只是一个例子)
I want to know if there is any direct method that can do this quickly. 我想知道是否有任何可以快速完成此操作的直接方法。
Pretty much anything is going to be slow with that large of a cell array. 对于那么大的单元阵列来说,几乎任何东西都会变慢。 You could try to do this with cellfun
but it's not necessarily guaranteed to be any faster than a for loop. 您可以尝试使用cellfun
执行此操作,但它不一定能保证比for循环更快。
a = cellfun(@(x)x(x ~= 1), a, 'UniformOutput', false);
% a{1} =
% 2 3
% a{2} =
% 5 3 6
% a{3} =
% 9 3
As already commented by Suever, because you are using a cell array and it is a dynamic container, you don't have a choice but to iterate through each cell if you want to modify the contents. 正如Suever已经评论过的那样,因为您正在使用单元格数组并且它是一个动态容器,所以如果要修改内容,则无法选择迭代每个单元格。 Just to be self-contained, here is the for
loop approach to do things: 只是为了自成一体,这里是for
循环方法来做事:
for ii = 1 : numel(a)
a{ii} = a{ii}(a{ii} ~= 1);
end
This may be faster as it doesn't undergo the overhead of cellfun
. 这可能会更快,因为它不会经历cellfun
的开销。 The code above accesses the vector in each cell and extracts out those values that are not equal to 1 and overwrites the corresponding cell with this new vector. 上面的代码访问每个单元格中的向量,并提取出那些不等于1的值,并用这个新向量覆盖相应的单元格。
Using your example: 使用你的例子:
a = {[1 2 3] [5 3 6] [9 1 3]};
We get: 我们得到:
>> format compact; celldisp(a)
a{1} =
2 3
a{2} =
5 3 6
a{3} =
9 3
This example shows how to remove data from individual cells, and how to delete entire cells from a cell array. 此示例显示如何从单个单元格中删除数据,以及如何从单元格数组中删除整个单元格。 To run the code in this example, create a 3-by-3 cell array: 要运行此示例中的代码,请创建一个3乘3的单元阵列:
C = {1, 2, 3; 4, 5, 6; 7, 8, 9};
Delete the contents of a particular cell by assigning an empty array to the cell, using curly braces for content indexing, {}: 通过为单元格指定一个空数组来删除特定单元格的内容,使用花括号进行内容索引,{}:
C{2,2} = []
This code returns 此代码返回
C =
[1] [2] [3]
[4] [] [6]
[7] [8] [9]
Delete sets of cells using standard array indexing with smooth parentheses, (). 使用带有平滑括号的标准数组索引删除单元格集()。 For example, this command 例如,这个命令
C(2,:) = []
removes the second row of C: 删除第二行C:
` `
C =
[1] [2] [3]
[7] [8] [9]`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.