Ternary conditions on Arrays/Matrices #2712
Replies: 11 comments
-
The conditional operator indeed doesn't support element wise operations. The reason is that you might want different behaviors, like should For your use case, you can use the function
|
Beta Was this translation helpful? Give feedback.
-
Any plan to implement an element wise version of the conditional operator? It could be useful to have a quick way other than the function to map an array of booleans with values, maybe with the usual element wise syntax
|
Beta Was this translation helpful? Give feedback.
-
Yes, I think it makes sense to re-evaluate this. In a very old version of mathjs, element wise operations on the conditional operator was returning the matching case also element wise, which was confusing. Interesting idea to introduce a new operator [true, false, true] ? [1,2] : [3,4]
[[1,2], [3,4], [1,2]] Optionally we could introduce a [true, false, true] ? [1,2,3] : [4,5,6]
[1, 5, 3] But I'm not sure if there is much need for this, and it can be done using a=[1,2,3]
b=[4,5,6]
map([true, false, true], f(x,i) = x ? a[i[1]] : b[i[1]]) |
Beta Was this translation helpful? Give feedback.
-
My idea to use |
Beta Was this translation helpful? Give feedback.
-
The only edge case would be when you use the conditional operator to see whether a variable contains "something" and if so do A, else do B. But I think the more common case is the one we're discussing now, and if you want to test whether a variable contains "something" you can explicitly test via |
Beta Was this translation helpful? Give feedback.
-
for our (mine and @SimoneTosato) application our need @josdejong is the one you indicated in your pointwise example: [true, false, true] ? [1,2,3] : [4,5,6]
[1, 5, 3] |
Beta Was this translation helpful? Give feedback.
-
@ddavidebor thanks for the feedback, good to hear that there are practical use cases. So we could go for my proposal at #718 (comment), implement a new operator |
Beta Was this translation helpful? Give feedback.
-
@josdejong yes please that would enable the usage of thernary conditions in our application |
Beta Was this translation helpful? Give feedback.
-
@ddavidebor the math.import({
iff: function (condition, truePart, falsePart) {
// ... element wise implementation of conditional operator ...
}
})
math.eval('iff([true, false, true] ? [1,2,3] : [4,5,6])'); // [1, 5, 3] |
Beta Was this translation helpful? Give feedback.
-
@josdejong yes of course we can work around that, but it's not as elegant and practical for the end user of something that works with the equation parser. |
Beta Was this translation helpful? Give feedback.
-
When I try something like
everything works fine, but with ternary conditions
isn't this supposed to return something like this?
Beta Was this translation helpful? Give feedback.
All reactions