在Matlab中交替的矢量块

时间:2017-05-12 16:31:28

标签: matlab

我在Matlab中有两个向量AB

我想构建一个向量C,其中我交替使用AB的块,其中一个块由一个非零元素和前面的所有0&#39组成; s回到之前的非零元素。

例如

A=[1 2 0 3 0 4 0 0 0 5]; %in chunks: {1}{2}{0 3}{0 4}{0 0 0 5} 
B=[6 7 8 9 10 11 0 12 0 0]; %in chunks: {6}{7}{8}{9}{10}{11}{0 12} 
C=[1 6 2 7 0 3 8 0 4 9 0 0 0 5 10];

或另一个例子

A=[0 0 4 9 9 9]; %in chunks: {0 0 4}{9}{9}{9}
B=[0 1 0 0 3 4 3 0 9 0 1 1 1]; %in chunks: {0 1}{0 0 3}{4}{3}{0 9}{0 1 1} 
C=[0 0 4 0 1 9 0 0 3 9 4 9 3];

你能帮我开发代码吗?

3 个答案:

答案 0 :(得分:4)

这是一种没有for循环的方法:

A=[0 0 4 9 9 9];
B=[0 1 0 0 3 4 3 0 9 0 1 1 1];

% Find indices where chunks end.
indsA = find(A~=0);
indsB = find(B~=0);

% Remove trailing zeros, since they are not part of any chunk.
A = A(1:indsA(end));
B = B(1:indsB(end));

% Get cell array of chunks. Use difference between successive last indices 
% of chunks to get the chunk sizes. Add a 0 dummy index to get the first
% chunk size.
chuncksA = mat2cell(A,1,diff([0,indsA]));
chuncksB = mat2cell(B,1,diff([0,indsB]));

% To take alternating chunks from each vector, we need to make sure we have
% an equal amount of chunks from each vector. This amount will be stored in 
% sz
sz = min(numel(chuncksA),numel(chuncksB));

% Sort the chunks by alternation, by combining the cell arrays on on top of
% the other, and then turning them into a column array by column-major 
% ordering
chuncks = [chuncksA(1:sz);chuncksB(1:sz)];
chuncks = chuncks(:)';

% convert back to vector
C = cell2mat(chuncks)

我建议您测试使用此方法对数据的更快或更慢。

答案 1 :(得分:1)

print h_layer1.get_shape()

答案 2 :(得分:0)

[~, posA] = find(A)
posA = [0,posA]
clear A_
for i = 1:length(posA)-1
    A_(i) = {A(posA(i)+1:posA(i+1))}
end

[~, posB] = find(B)
posB = [0,posB]
clear B_
for i = 1:length(posB)-1
    B_(i) = {B(posB(i)+1:posB(i+1))}
end

clear C_
for i = 1:min(length(A_), length(B_))
    C_(i) = {{A_{1,i},B_{1,i}}};
end
C = cell2mat([C_{:}])