Vadim Tor
Vadim Tor

Reputation: 40

Fill big array with data from smaller arrays

i need to fill big array with several smallers arrays. Data from the small one filling the big array starting from the concrete index. For example:

a = [0 0 0 0 0 0 0 0 0 0];
b = [1 2 3 ];

r = [0 0 0 1 2 3 0 0 0 0];

In the addition, it should be done the way that would allow crossing data to sum up and not to overwrite, like this:

a = [0 0 0 1 2 3 0 0 0 0];
c = [3 2 1];

r = [0 3 2 2 2 3 0 0 0 0];

Thanks.

Upvotes: 0

Views: 219

Answers (2)

Dev-iL
Dev-iL

Reputation: 24179

It's actually quite simple:

function q41370447
  ind = [4, 2];
  a = zeros(1,10);
  b = 1:3;
  c = 3:-1:1;

  a = addFromIndex(a,b,ind(1));
  % [0,0,0,1,2,3,0,0,0,0]
  a = addFromIndex(a,c,ind(2));
  % [0,3,2,2,2,3,0,0,0,0]
end

function largeVec = addFromIndex(largeVec,smallVec,startIndex)
  n = numel(smallVec);
  largeVec(startIndex:startIndex+n-1) = largeVec(startIndex:startIndex+n-1) + smallVec;
end

Upvotes: 1

Alamakanambra
Alamakanambra

Reputation: 7881

a=[0 0 0 1 2 3 0 0 0 0];
c=[3 2 1];

your_concrete_index = 2;
cc = zeros(1,length(a)); %same length, filled with zeros
cc(your_concrete_index:your_concrete_index+length(c)-1) = c;%from index, whole c
a_result = a+cc; % just sum..

Upvotes: 0

Related Questions