0
$\begingroup$

Is there any way to write a code that has a function include Block[ ] and Do[ ] loop instead of my code?

Here is my code:

(* m = Maximum members of "list" *)
list = {{12, 9, 10, 5}, {3, 7, 18, 6}, {1, 2, 3, 3},
   {4, 5, 6, 2}, {1, 13, 1, 1}};
m = {};
Do[
  AppendTo[m, Max[list[[All, i]]]];
  , {i, 1, Length[list[[1]]]}];
m
(*{12,13,18,6}*)
$\endgroup$
4
  • 3
    $\begingroup$ You can get the same result using Max/@Transpose@list $\endgroup$
    – ZaMoC
    Commented Oct 27, 2018 at 20:57
  • $\begingroup$ @J42161217 Thank you, I just wanted to write it by using functions. $\endgroup$
    – Rhun Rhun
    Commented Oct 27, 2018 at 21:10
  • $\begingroup$ Is this a homework question? Why are you forced to use those 2 functions? $\endgroup$
    – ktm
    Commented Oct 27, 2018 at 22:04
  • $\begingroup$ @user6014 No, Its just an alternate code to do same thing $\endgroup$
    – Rhun Rhun
    Commented Oct 28, 2018 at 13:35

2 Answers 2

1
$\begingroup$
ClearAll[f]
f[l_List] := Block[{m={}, i=1}, Do[AppendTo[m, Max[l[[All, i++]]]], {Length @ l[[1]]}]; m]

f[list]

{12, 13, 18, 6}

$\endgroup$
3
$\begingroup$

if you want to use your code try

F[list_] := Block[{m}, m = {};
Do[AppendTo[m, Max[list[[All, i]]]];, {i, Length[list[[1]]]}];m]

F[list]   

otherwise you can use this function

F[list_]:=Max/@Transpose@list
$\endgroup$
1
  • 1
    $\begingroup$ As Do scopes its iterator, there is no need to scope the i... $\endgroup$ Commented Oct 27, 2018 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.