Maurício Pires
Maurício Pires

Reputation: 75

Matlab Insert NaN into array

I need to insert NaNs into in specific positions of an array. I wrote the code that is correctly doing it, but as I need to do it for really large arrays, it's taking too long to run. Numpy has the function insert(i, x) that inserts an item at a given position. Is there a similar function in Matlab? Or is there a more efficient way to do it?

a = [1 2 3 5 6 7 9 10 13 14];
insertNanIndex = [0 1 0 1 1 0 0 0 1 1 0 0 1 0 0 0];

for i = find(insertNanIndex)
    a = [a(1:i-1), NaN, a(i:end)]
end

Upvotes: 2

Views: 306

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114330

The efficient way to do this would be to pre-compute the size of the result, make sure that insertNanIndex was large enough to serve as a mask, and insert a into the correct indices all at once. Right now, you are literally re-allocating the entire array for every NaN. Numpy's insert function would be equally inefficient because it would be doing the same operation.

If, as in your example, the number of zeros matches the number of elements of a, you can allocate an array based on insertNanIndex and mask it directly:

result = nan(size(insertNanIndex));
result(~insertNanIndex) = a;

If the number of zeros in insertNanIndex is not equal to the size of a, you can pad or trim it, but in that case, it becomes more of a moot point as to what the whole thing means.

Upvotes: 4

Related Questions