Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab: inserting element after element?

Is there a way to insert an element into an array after verifying a certain element value? For example, take

A = [0 0 1 1 0 1 0] 

After each 1 in the array, I want to insert another 1 to get

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

However I want a way to code this for a general case (any length 1 row array and the ones might be in any order).

like image 433
phomein Avatar asked Oct 09 '12 04:10

phomein


People also ask

How do you add an element to a element in Matlab?

C = A + B adds arrays A and B by adding corresponding elements. If one input is a string array, then plus appends the corresponding elements as strings. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

What is %s in Matlab?

%s represents character vector(containing letters) and %f represents fixed point notation(containining numbers). In your case you want to print letters so if you use %f formatspec you won't get the desired result.


3 Answers

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
like image 111
Zero Avatar answered Oct 12 '22 11:10

Zero


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...

like image 39
bla Avatar answered Oct 12 '22 11:10

bla


This should do the trick:

>> 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
like image 37
Rody Oldenhuis Avatar answered Oct 12 '22 10:10

Rody Oldenhuis