Message Boards Message Boards

0
|
6082 Views
|
5 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Use Apply[] when f has 2 or more functions?

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?

POSTED BY: Manjunath Babu
5 Replies
Posted 8 years ago

Is this what you want?

 (Max[#] - Min[#]) & /@ {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}}  
POSTED BY: Okkes Dulgerci

Yes. But, how do i use Apply[] function that can apply on more than 1 function in its arguments?

POSTED BY: Manjunath Babu

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

Yes, this is perfect. Thank you so much for explaining about the ## SoltSequence sign

POSTED BY: Manjunath Babu

Comment, The Apply needs to be at level 1, that is, use @@@ as its shortcut. I edited my previous answer above

best

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract