MATLAB: How to replace a range in one array at a specific location using the value of another array to determine where

arrayindexreplacezeros

I have two arrays (both are 1 column):
  1. ArrayZeros – this array is filled with 400,000 zeros.
  2. ArrayInput – this array has 20 values.
My goal is iterate through ArrayInput and use those numbers to determine were in ArrayZeros I should replace with the number '4'. This number in ArrayInput would be the start location, and I want to replace 20 0's with 20 4's. For example, if ArrayInput's first number is 8 then I want to go to the eighth location in ArrayZeros and replace with a 4 and continue until the 28th zero. This will change ArrayInput from 8-28th location to 4's. I would want to keep iterating through ArrayInput and continue to change ArrayZeros.

Best Answer

I believe this does what you need.
ArrayZeros = zeros(400000,1); %this array is filled with 400,000 zeros.
ArrayInput = [5 40 230]; % this array has 20 values (but using 3 values to illustrate).
PositionsToFill = 20;
for na = 1:numel(ArrayInput)
anchor = ArrayInput(na);
ArrayZeros(anchor:anchor+PositionsToFill-1) = 4;
end