Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing values of specific entries in an Array In Julia

I am wondering about how to implement efficiently a code that replaces some entries of an array with specific values. In other words, I have a matrix and a vector with some indices of the matrix where a logical condition holds. I want to change these entries for some values that I have in a vector.

So far, I've doing it with a loop, but perhaps there is a better strategy that uses filtering or something like that.

A small example would be:

A = collect(1:8); println(A)
   B = [10,20]
   C = A.<=2
   k = 1
   for t=1:8
                if C[t] ==  1
                    A[t] = B[k]
                    k = k+1
            else
       end
    end

However, I need to do this in inside a quite intensive loop, with a bigger matrix. The indices I have to change are always the same, but the vector of values (the counterpart of B) changes in each iteration.

Thanks so much!

like image 679
econ_ugrad Avatar asked Oct 18 '25 11:10

econ_ugrad


1 Answers

You can simply write:

A = collect(1:8)
B = [10,20]
C = findall(A.<=2)
A[C] = B

The use of findall function could be also rewritten as C = findall(x -> x <= 2, A) to reduce the number of allocations. The key is that it is better that C holds actual indices than logical indices. Technically A[C] = B would also accept logical indices in C but then it is slower. And assuming that C is computed once while A[C] = B is computed many times it is better to precompute the indices you want to use.

If C changes with every iteration then it might be better to write C .= A .<= 2 and then A[C] = B (note that I use in-pace update of C here as when it is updated many times it is faster). You would have to benchmark what is better in your specific case.

like image 73
Bogumił Kamiński Avatar answered Oct 21 '25 04:10

Bogumił Kamiński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!