0

I often encounter situations where I can easily think of python code that, given some input values, computes multiple output values at once. As an example, consider the following simple code-block that converts the real and imaginary part (a and b) of a complex number to its polar representation (radius and phase). In an org-mode file I would write:

#+name: radius_phase_conv 
#+begin_src python :exports none :var a=2. :var b=2.
  from cmath import polar
  from math import degrees
  num = complex(a,b)
  r, phi = polar(num)
  phi_deg = degrees(phi)
  return round(r,5), round(phi_deg,5)
#+end_src

#+RESULTS: radius_phase_conv
| 2.82843 | 45.0 |

Now I want to use such a code on a table in org-mode that contains the columns with the input values. In above example, we might have a table with a and b.

|      a |       b | 
|--------+---------|
|      1 |       0 | 
|      1 |       1 | 

Putting the line

#+TBLFM: $3='(org-sbe "radius_phase_conv" (a $1) (b $2)

below the table, will produce a 3rd column that contains the tuples with the radius and the phase.

|      a |       b |                    |
|--------+---------+--------------------|
|      1 |       0 | (1.0 0.0)          |
|      1 |       1 | (1.41421 45.0)     |
#+TBLFM: $3='(org-sbe "radius_phase_conv" (a $1) (b $2))

How do I need to alter the #+TBLFM: + org-sbe statement in order to produce two columns in the final table, i.e. the desired result would be

| a | b |          |       |
|---+---+----------+-------|
| 1 | 0 | 1.0      |  0.0  |
| 1 | 1 | 1.41421  | 45.0  |
#+TBLFM: ???
0

How about breaking it into two functions and have

$3='(org-sbe radius...)::$4='(org-sbe phase...)

Or keeping one function but passing in a 3rd argument that tells it what value you want returned? Not ideal...

Or don't use TBLFM? What about calling radius_phase_conv and passing in the a|b table (after you NAME it), and then having Python print out the four-column table for you?

  • Breaking it into two functions is what I use at the moment, but it is not elegant, since I have to duplicate code that does essentially the same. The second solution is what I used in the past, but it is also not very elegant, as I will have column a and b occurring twice in the org-file, i.e. if I want to change a value in a or b, I have to do it in another table. – Christian Herenz Sep 18 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.