我有一个单元数组(11000x500),它有三种不同类型的元素。1)非零双精度2)零3)空单元格
我想找出所有出现在两个零之间的非零数。
例如,A = {123 13232 132 0 56 0 12 0 0 [] [] []};
我需要以下输出out = logical([0 0 0 0 1 0 1 0 0 0 0 0]);
我像这样使用cellfun和isequal
out = cellfun(@(c)(~isequal(c,0)), A);并得到了以下输出
out = logical([1 1 1 0 1 0 1 0 0 1 1 1]);我需要帮助来执行下一步,我可以忽略连续的1's,只取两个0's之间的‘1’
有没有人能帮我一下?
谢谢!
发布于 2016-09-06 00:59:56
您可以使用conv查找邻居为0的元素(请注意,该~已从isequal中删除):
out = cellfun(@(c)(isequal(c,0)), A); % find 0 elements
out = double(out); % cast to double for conv
% elements that have more than one 0 neighbor
between0 = conv(out, [1 -1 1], 'same') > 1;
between0 =
0 0 0 0 1 0 1 0 0 0 0 0(卷积内核已更正,以修复@TasosPapastylianou发现的错误,其中3个连续的零将导致True。)
如果你想要一个逻辑向量的话。如果需要索引,只需添加find
between0 = find(conv(out, [1 -1 1], 'same') > 1);
between0 =
5 7发布于 2016-09-06 00:41:09
下面是使用out执行此操作(以及其他二进制数据操作)的快速方法
out = logical([1 1 1 0 1 0 1 0 0 1 1 1]);
d = diff([out(1) out]); % find all switches between 1 to 0 or 0 to 1
len = 1:length(out); % make a list of all indices in 'out'
idx = [len(d~=0)-1 length(out)]; % the index of the end each group
counts = [idx(1) diff(idx)]; % the number of elements in the group
elements = out(idx); % the type of element (0 or 1)
singles = idx(counts==1 & elements==1)你将会得到:
singles =
5 7从这里开始,您可以继续并根据需要创建输出:
out = false(size(out)); % create an output vector
out(singles) = true % fill with '1' by singles然后你会得到:
out =
0 0 0 0 1 0 1 0 0 0 0 0发布于 2016-09-06 00:56:25
另一种解决方案,这完全避免了你的初始逻辑矩阵,我认为你不需要它。
A = {123 13232 132 0 56 0 12 0 0 [] [] []};
N = length(A);
B = A; % helper array
for I = 1 : N
if isempty (B{I}), B{I} = nan; end; % convert empty cells to nans
end
B = [nan, B{:}, nan]; % pad, and collect into array
C = zeros (1, N); % preallocate your answer array
for I = 1 : N;
if ~any (isnan (B(I:I+2))) && isequal (logical (B(I:I+2)), logical ([0,1,0]))
C(I) = 1;
end
end
C = logical(C)C =
0 0 0 0 1 0 1 0 0 0 0 0https://stackoverflow.com/questions/39334577
复制相似问题