mababu
(Manjunath Babu)
October 22, 2016, 11:03pm
1
Consider the following line of code that operates on a list of lists.
This code finds the Maximum element in each list of lists.
In[1]:= Apply[Max, {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}}, 1]
Out[1]:= {3, 5, 9}
This code finds the Minimum element in each list of lists.
In[2]:= Apply[Min, {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}}, 1]
Out[2]:= {1, 4, 6}
But how do I find Max - Min for each list in the “list of lists” using Apply[] only ?
scinar
(Okkes Dulgerci)
October 23, 2016, 12:13am
2
Is this what you want?
(Max[#] - Min[#]) & /@ {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}}
mababu
(Manjunath Babu)
October 23, 2016, 12:31am
3
Yes. But, how do i use Apply[] function that can apply on more than 1 function in its arguments?
benshimo
(Yehuda Ben-Shimol)
October 24, 2016, 5:09pm
4
The solution offered by Okkes will not work if you use Apply. the reason is that both Max and Min use only the first argument (the # sign), so if you try (@@ is the shortcut for Apply and @@@ for Apply at level 1)
(Max[#] - Min[#]) @@@ {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}}
you will get {0,0,0} as the answer
So, you need to take care that both Max and Min will enclose all the arguments and for that you need to use ## (SlotSequence stand for “all arguments”, see documentation). So
(Max[##] - Min[##]) & @@@ {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}}
returns {2,1,3} as expected, and probably this is what you are looking for
yehuda
mababu
(Manjunath Babu)
October 25, 2016, 3:52am
5
Yes, this is perfect. Thank you so much for explaining about the ## SoltSequence sign
benshimo
(Yehuda Ben-Shimol)
October 25, 2016, 5:00am
6
Comment,
The Apply needs to be at level 1, that is, use @@@ as its shortcut. I edited my previous answer above
best