简体   繁体   中英

Insert new values in to array

In Matlab, I have an array that has labels, for example

Events = [10; 11; 41; 42; 31; 32; 41; 42]; 

I want to edit this array so that after each 41 I insert 8 411 s such that I end up with:

New_events = [10; 11; 41; 411; 411; 411; 411; 411; 411; 411; 411; 42; 31; 
              32; 41; 411; 411; 411; 411; 411; 411; 411; 411; 42];

Is there a simple way to do this?

I have used find to get the indices of each occurrence of 41 but am unsure how to preserve the order of the other labels... Does anyone know how I could do this?

I have just posted a small example of the what the array looks like but in reality, it is much bigger and I need to do this many times (appx 200 times) so I need something automated...

Thanks

Find all 41, and iterate over them. Just, after each insertion, add 8 to the next index of 41:

finds_41 = find(Events == 41).';
counter = 0;
for idx = finds_41
    pos_41 = idx + counter*8
    Events = [Events(1:pos_41); 411 * ones(8,1); Events((pos_41 + 1):end)];
    counter = counter + 1;
end

You can do this by creating a Boolean for each insertion point ( Events==41 ) then using repmat to repeat 411 either 8 or 0 times.

Then arrayfun makes the code pretty short

Events = [10; 11; 41; 42; 31; 32; 41; 42];
out = arrayfun( @(x,b) [x; repmat(411, 8*b, 1)], Events, Events == 41, 'uni', 0 );
out = vertcat(out{:});

This might work. But I sort of hope there is a simpeler solution to this problem. What you want to do seems so simple.

clear all
Events = [10; 11; 41; 42; 31; 32; 41; 42];
Insert = [411; 411; 411; 411; 411; 411; 411; 411];
atval = 41;

Nin=numel(Insert);
idx = [0;find(Events==atval)];
out = nan(length(Events)+Nin*(length(idx)-1),1);
for ct = 2:length(idx)
    out(Nin*(ct-2)+[1+idx(ct-1):idx(ct)])=Events(1+idx(ct-1):idx(ct)); %copy events
    out(Nin*(ct-2)+idx(ct)+1:Nin*(ct-2)+idx(ct)+Nin)=Insert; %put insert
end
out(Nin*(ct-1)+[1+idx(ct):length(Events)])=Events(1+idx(ct):end); %copy last events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM