3
$\begingroup$

I'm asked to create a For[] loop that will sum positive numbers in a list. I am unsure of how to do this.

For[i = 0, i <= Length[List], i += 1, result += i];

result

This is what i have so far where List is the list of numbers and result is the summation of all the positive numbers. I am aware this is not right though.

$\endgroup$
7
  • 2
    $\begingroup$ Just to get it out of the way: see this and this. Apart from class exercises, you shouldn't need to use For[]. $\endgroup$ Commented May 16, 2020 at 9:05
  • $\begingroup$ do you have example of such a list that you want to sum? $\endgroup$
    – Nasser
    Commented May 16, 2020 at 9:17
  • 6
    $\begingroup$ Better use Total@*Ramp... It is vectorized and thus much more efficient thatn top-level loops. $\endgroup$ Commented May 16, 2020 at 9:33
  • 2
    $\begingroup$ A variation of @Henrik's proposal is list.Unitize[Ramp[list]]. $\endgroup$ Commented May 16, 2020 at 11:24
  • 2
    $\begingroup$ and so list.UnitStep@list $\endgroup$ Commented May 16, 2020 at 13:08

3 Answers 3

5
$\begingroup$
bill = {3, -5, 2, -12, -4, -1, -8, 10};
Total[Select[bill, # > 0 &]]

An even shorter way, from this question, is

Total[Select[bill, Positive]]

The answer is 15. I believe that covers the OP's request, but it might be something more complicated. On documentation,

https://reference.wolfram.com/language/ref/Select.html

$\endgroup$
0
4
$\begingroup$

List={3, -5, 2, -12, -4, -1, -8, 10}

There are many ways to do this in Mathematica, without using For.

One way could be to first filter out the positive numbers, then call Total

list = {3, -5, 2, -12, -4, -1, -8, 10};
positiveNumbersOnly = Cases[list, x_ /; Positive[x] -> x]

(*{3, 2, 10}*)

Total[positiveNumbersOnly]

(* 15*)

You can combine the above into one call

 Total@Cases[list, x_ /; Positive[x] -> x]

I am sure one can come up with 10 other ways to do this if needed.

For example

 Total[If[# > 0, #, 0] & /@ list]
 (* 15 *)

Another is

 Total[Clip[list, {0, Infinity}]]
 (* 15 *)
$\endgroup$
1
  • 2
    $\begingroup$ If using Cases[], you could just do Cases[list, x_?Positive]. $\endgroup$ Commented May 16, 2020 at 11:22
3
$\begingroup$

It's just for fun.

{3, -5, 2, -12, -4, -1, -8, 10} //. {b_, c_, a___} :> {Ramp[b] + Ramp[c], a}//First
$\endgroup$

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.