Matlab:如何在数组中重新插入元素?

时间:2016-06-17 00:59:10

标签: arrays matlab insert

我的原始数组是A = [1 0 2 3 0 7]。我删除了零中的索引,得到A = [1 2 3 7]。我将删除的元素的索引存储在名为DEL = [2 5]的数组中。

如何在数组中重新插入零以取回原始数组?

3 个答案:

答案 0 :(得分:2)

这将为你做到:

A = [1 2 3 7];
DEL = [2 5];

n = numel(A) + numel(DEL);

B = zeros(1,n);
mask = true(1,n);
mask(DEL) = false;
B(mask) = A;

或者,您可以使用以下方法在一行中设置遮罩:

mask = setdiff(1:n, DEL);

结果:

B =

   1   0   2   3   0   7

答案 1 :(得分:1)

A = [1 0 2 3 0 7] ;
A_ = [1 2 3 7] ;
[~,i] = find (A) ;
B = zeros (1,length(A)) ;
B(i) = A_ ;

答案 2 :(得分:1)

A = [1 2 3 7]; 
DEL = [2 5];

array_indices = 1:6;      % the indices of the original array
array_indices(DEL) = [];  % indices of numbers that were not deleted
B = zeros(1,6);           % created zeros of the same length as original array
B(array_indices) = A;     % replace zeros with non-zero #s at their locations