wolfram mathematica - Changing values in nested lists according to elements in the list -


I have a list of values ​​in mathematics, for example List = {{3,1} , {5,4}} .

If the second element does not reach a threshold, then how do I change the first element (3 & 5)? For example, if the second part is below 2 then I would like the first parts to go to zero. So list == {{0,} {5,4}} . Unfortunately, some of these lists are doing manually for a very long time, unfortunately there is not an option.

Conceptually, in the normal way, in your case, code

  will be [13]: = lst = {{3, 1}, {5, 4}} outside [13] = {{3, 1}, {5, 4}} in [14]: = thr = 2 out [14] = 2 in [15]: = map [[if [# [[2]]   

The # symbol here stands for argument. You can read more on pure functions, double square brackets stand for extraction. You can make it a little more condensed by using level 1, which is shortened by @@@ :

 in  [27]: = {if # [2] & lt; Thr, 0, #], # 2} & amp; @@@ lst Out [27] = {{0, 1}, {5, 4}}   

However, note that the first method is several times faster for large numerical lists. There is one fast, but some more obscure method is:

  in [29]: = change [{# [all, 1]] * unit stop [# [[All, 2]] - thr], # [[All, 2]]}] & amp; [Lst] out [29] = {{0, 1}, {5, 4}}   

It is fast because it uses very optimized vector-operated operations which Applies to all sub-lists in Finally, if you want the final performance, then this process compiled in the C version will have another aspect of more than 2:

  fn = compile {{{{}}, the module [ For {copy = lst, i = 1}, [i = 1, i & lt; = Length [lst], i ++, if [copy [[i, 2]] & lt; Threshold, copy [[i, 1]] = 0]]; Copy], collection-target - & gt; "C", Runtime Option - & gt; "[Speed"]   

You used it in

  [32]: = fn [lst, 2] out [32] = {{, 1}, {5, 4}}   

For this last one, you need to install C compiler on your machine.

Comments

Popular posts from this blog

qt - switch/case statement in C++ with a QString type -

python - sqlite3.OperationalError: near "REFERENCES": syntax error - foreign key creating -

Python's equivalent for Ruby's define_method? -