使用较小数组中的数据填充大数组

时间:2016-12-28 22:14:34

标签: arrays matlab

我需要用几个小型数组填充大数组。从具体索引开始填充大数组的小数据。例如:

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];

此外,它应该采用允许交叉数据总结而不是覆盖的方式,如下所示:

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];

感谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

实际上非常简单:

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