Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I want to program a code in MATHEMATICA in order to calculate some values in different iteration. For example, assume this list:

list={1,2,3,4,5}

Now assume that the function is :

f1=Function[u,3+u][x]

I want to use a Do loop to orderly put each integer from the list into f1 function and Do loop uses 5 iteration ({i,1,5}) and gives 5 answers using the values in the list. For this example, The results will be :

4 5 6 7 8

I wonder if anyone could help me with this problem.

share|improve this question
    
My guess is that you have tried something along the lines of Do[f1[list[[x]]],{x,5}] and that you got nothing as output. Try telling it to Print the output by wrapping the f1[list[[x]]] with Print[]. The answer that Christopher Cole provided using Map is clearly a better way to solve this. –  Andy Mobley Mar 30 at 15:46

1 Answer 1

up vote 2 down vote accepted

I think you want to define f1 as

f1 = Function[u, 3 + u]

since the form you started with would have created the function and then applied it to x.

The easiest way to do what you want is to use Map:

Map[f1, list]

which has an equivalent syntax

f1 /@ list

If you really must use a Do loop, you would do it as follows:

Module[{result = {}}, Do[AppendTo[result, f1[i]], {i, list}]; result]

This is a lot more work. The Module that wraps the Do loop creates a result symbol to hold your output. The Do loop iterates over the elements of list, appending the computation of f1 on each element to the result output.

share|improve this answer
    
@ Christopher Thank you so much!! –  Shellp Mar 31 at 6:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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