2

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. But I'm getting the following error on the last line: Unable to perform assignment because the left and right sides have a different number of elements.
Great! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.