Generate all possible combinations of a few variables of a maximum length using certain mathematical operators/functions?
Show older comments
I’m trying to do something that shouldn’t be impossible but is a bit cumbersome and tricky for me to figure out how to write: I want to first define a set of mathematical operators/functions that I allow, for example lets say I allow +, -, *, / and cos() of a variable (so, addition, subtraction, multiplication, division and cosine in other words). And I have a number of variables, lets say a and b to keep it simple.
I would like to generate all possible combinations of a and b that can be calculated using these allowed operators but whilst keeping the expression under a specific length. So say I want to limit the length to only allow the usage of a maximum of two variables, it could be that a is used two times, a is used one time, b is used two times, b is used one time or that a and b are together used to generate the combination.
To give and example of what I mean – using the rules I have stated above in my example, a and b would generate the following combinations:
a
b
a+b
a+a
b+a
b+b
a-a
a-b
b-a
b-b
a*a
a*b
b*b
b*a
a/a
a/b
b/a
a/b
b/b
cos(a)
cos(b)
cos(a)+b
cos(a)-b
cos(a)*cos(b)
a/cos(b)
cos(b)/cos(a)
…
…
And so on and so on. Even with just two variables and five allowed operators the number of combinations become pretty much too many to manually list, but I hope you understand what I want to create.
If this is possible to create I would also like to be able to add more allowed operators, so for example sin(), sqrt(), tan(), mean(),log(), exp() and so on. And I would also like to be able to generate the combinations with more than two variables and with a slightly longer allowed max length, for example 3 or 4 variable usages.
Is this in any way possible to generate?
Thanks in advance.
1 Comment
Stephen23
on 8 Feb 2016
Do you want a numeric or symbolic output?
Accepted Answer
More Answers (1)
Joseph Cheng
on 8 Feb 2016
Edited: Joseph Cheng
on 8 Feb 2016
0 votes
This is certainly possible and to perform this easily i'd tackle this in two parts.
- create function to perform single variable operations the sin(), cos(), tan(), sqrt()... with input of variable to be operated
- another function for inbetween operations (+,-,/,...) with input of two variables to be operated on.
each function would also take in a number which you'll use as a switch/case statement to get the output.
With something like this you can write nested for loops to go through combinations for however many variables.
1 Comment
Peta
on 8 Feb 2016
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!