Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating values in an array with logical indexing with a non-constant value

Tags:

arrays

matlab

A common problem I encounter when I want to write concise/readable code:

I want to update all the values of a vector matching a logical expression with a value that depends on the previous value.

For example, double all even entries:

weights = [10 7 4 8 3];
weights(mod(weights,2)==0) = weights(mod(weights,2)==0) * 2;
% weights = [20 7 8 16 3]

Is it possible to write the second line in a more concise fashion (i.e. avoiding the double use of the logical expression, something like i+=3 for i=i+3 in other languages). If I often use this kind of vector operation in different contexts/variables, and I have long conditionals, I feel that my code is less concise and readable than it could be.

Thanks!

like image 352
Hottemax Avatar asked Dec 03 '25 02:12

Hottemax


2 Answers

How about

ind = mod(weights,2)==0;
weights(ind) = weights(ind)*2;

This way you avoid calculating the indices twice and it's easy to read.

like image 200
Wauzl Avatar answered Dec 05 '25 17:12

Wauzl


Starting your other comment to Wauzl, such powerful operation capabilities is the Fortran side. This is purely matlab's design that is quickly getting obsolete. Let's use this horribleness further:

for i=1:length(weights),if (mod(weights(i),2)==0)weights(i)=weights(i)*2;end,end

It is even slightly faster than your two liner because you are doing the conditional indexing twice on both sides. In general, consider switching to Python3.

like image 44
percusse Avatar answered Dec 05 '25 15:12

percusse



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!