Write reduce function, that takes arguments and constantly folds results into next call argument, finally returning a value; i.e. for a binary operator Fb,
reduce(Fb,{a,b,c},start_val) = F(F(F(start_val,a),b),c)Same can be done for a n-ary operators.
Eg. reduce(@strcat,{'foo','bar','baz','bat'},' ') = reduce(@plus,{1,2,3,4},0) = 10 reduce(@max,{1,2,3,4},{5,6,7,8},5) = 8
Remember, we use cell arrays for passing arguments, not matrices!
Solution Stats
Problem Comments
Solution Comments
Show commentsProblem Recent Solvers20
Suggested Problems
-
Remove all the words that end with "ain"
2712 Solvers
-
chance in percent for minimum K heads when a good coin is tossed N times?
55 Solvers
-
Back to basics 13 - Input variables
395 Solvers
-
Convert a numerical matrix into a cell array of strings
2532 Solvers
-
Find the maximum number of decimal places in a set of numbers
3563 Solvers
More from this Author10
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
could you separate your asserts into multiple cells so you can see which test case is failing?
also, how do you define the n-ary behavior since max only takes up to 2 non-empty arguments?
I mean, n-ary operators are also supported, but I use max as a binary op.