6

有没有办法在验证某个元素值后将元素插入到数组中?例如,取

A = [0 0 1 1 0 1 0] 

在数组中的每个 1 之后,我想插入另一个 1 以获得

Anew = [0 0 1 1 1 1 0 1 1 0] 

但是,我想要一种针对一般情况进行编码的方法(任何长度为 1 的行数组,并且这些数组可能按任何顺序排列)。

4

3 回答 3

5
A = [0 0 1 1 0 1 1];

i = (A == 1);  % Test for number you want insert after
t = cumsum(i);              
idx = [1 (2:numel(A)) + t(1:end-1)];

newSize = numel(A) + sum(i);
N = ones(newSize,1)*5;             % Make this number you want to insert

N(idx) = A

Output:

N =

     0     0     1     5     1     5     0     1     5     0

I made the inserted number 5 and split things onto multiple lines so it's easy to see what's going on.

If you wanted to do it in a loop (and this is how I would do it in real life where no-one can see me showing off)

A = [0 0 1 1 0 1 0];

idx = (A == 1);  % Test for number you want insert after
N = zeros(1, numel(A) + sum(idx));
j = 1;
for i = 1:numel(A)
    N(j) = A(i);
    if idx(i)
        j = j+1;
        N(j) = 5;       % Test for number you want to insert after
    end
    j = j+1;
end

N

Output:

N =

 0     0     1     5     1     5     0     1     5     0
于 2012-10-09T05:05:29.683 回答
2

这应该可以解决问题:

>> A = [0 0 1 1 0 1 0] 
>>
>> sumA = sum(A);
>> Anew = zeros(1, 2*sumA+sum(~A));
>> I = find(A) + (0:sumA-1);
>> Anew(I) = 1;
>> Anew(I+1) = 8.2;

Anew =
    0  0  1  8.2  1  8.2  0  1  8.2  0
于 2012-10-09T07:42:55.817 回答
2

This code is not the most elegant, but it'll answer your question...

 A=[0 0 1 1 0 1 0];
 AA=[];
 for ii=1:length(A);
     AA=[AA A(ii)];
     if A(ii)
         AA=[AA 1];
     end
 end

I'm sure there will be also a vectorized way...

于 2012-10-09T05:05:04.250 回答