How do you do array calculations?

I stumbled into the wish to do array calculation (at least some basics like element-wise multiplication, multiplication by float, substraction, …).
Especially when doing some cetz plots it would make some coordinate calculations much easier.

According to Array Type – Typst Documentation only addition and multiplication by an integer can be done in typst.
While I do not really understand the reasons (an explanation would be nice just to understand whether this is something on the roadmap or intended by design) I would like to know how others are solving this.

  • Are you writing custom functions that you reuse?
  • Are you doing it element wise “by-hand”?
  • Is there any package I’m not aware of?
  • Am I wrong and there is a typst way to do it?

Hi @Max1, welcome to the forum! I have edited the title of your question to follow our guidelines.

Note that the “addition” and “multiplication” of several arrays in Typst are not mathematical operations: array1 + array1 will concatenate the arrays and array1 * 3 will concatenate 3 copies of array1.

For actual math operations, you have the functions array.sum and array.product that operate on the elements of an array:

#(1,2,3).product()  // returns 6

For operations with several arrays, you can use arrays functions like map, zip and fold to implement some of them easily. For example the sum of two vectors:

#let a = (1, 2, 3)
#let b = (0, 10, 100)

// Returns (1, 12 ,103)
#a.zip(b).map(array.sum)

I recently posted an example implementation of matrix multiplication along these lines: Minimal implementation of matrix multiplication

For heavy usage you can try to find a package that implements what you need. At some point there will probably be a comprehensive numerical package in the form of a WebAssembly plugin but I don’t think we’re there yet. But CeTZ itself has a lot of vector and matrix functions that you can access with cetz.util.vector and cetz.util.matrix. See for example here for the vector documentation. Note that these functions are documented as internals, so I guess they might change even in minor updates of the CeTZ package.

1 Like

Thanks a lot for the answer.

Obviously misunderstood the part about addition and multiplication and didn’t test it enough to see the mistake :man_facepalming:

I knew about the array.sum and array.product functions but didn’t think much further. Quite elegant way how you implemented the basic stuff. Never came into my mind doing it that way :sweat_smile: Thanks a lot :blush:

Also thanks for the hint to cetz internals.

1 Like