I have a 2d matrix, is there a method to simply add up all the values together?
Yes, just drop the list onto the arrows in the (() + () @delInput @verticalEllipsis @addInput)
block.
If you have a list of lists that you want to add up/ you may need to use [sb] ([columns V] of @list) [sb], because it adds each item in each list together (so [1][1] + [2][1], etc).
The OP has a 2D array and wants a single number as answer. So it'd be
(FLATTEN is one of the options in the LENGTH OF block's menu.)
didnt this use to be a primitive in the list OF menu or something
No, and I don't even know what you could even be remembering.
oh ok
In one version, there used to be a Σ (Sigma) option in the ([ V] of @list)
block which works similarly to summing the values of the list in a (sum @verticalEllipsis @addInput)
block.
It is added in 9.2.14 only to be removed one patch version later in 9.2.15.
Ah, I still see it in the code of Snap!. I think he removed it but kept functionality?
Edit: yep.
I suspect Σ didn’t really fit into the group of list operations offered by the block, as Σ is only meaningful for lists consisting of numbers, whereas the other operations (length .. reverse, text .. json) are relevant with any list. And, indeed, sum
and flatten
, combined make a good alternative solution.
BTW: I wonder how @tethrarxitet managed to insert a Σ into the first slot.
Alternatively, you can edit the block's dropdown to be editable, insert that, and change it back to be read-only.
you can always use code to blocks to code (or what @mobility212 did, of course)
Or, you can:
sum(sum(array))
This is actually faster when dealing with (extremely) large lists/arrays.
For a list with unknown rank, you can do this (cascade block taken from iteration, composition library):
Yeah, good point. Now that you mention it, of course it avoids making a temporary copy of the array. That's how I actually did it first, but I chose the FLATTEN solution because it generalizes to arrays of any rank.
Another multi-level solution:
with a reporter-let
block:
Edit
The following deep (list operation)
block makes for a very general solution:
It completely differs from the APL library’s in that it transforms (sub-)lists, not “atoms”.
It is also, subtly, different from applying the referenced list operation on the flattened list:
another way:
On the topic of matrices, is there a method to calculate the variance of a 2d matrix
Well how would you normally calculate it in math?
under "Math tools" in the SciSnap! library
do you know what this error means
Yes, you didn't load the scisnap library (or initialize it).