1

I am having truble understanding why F1 produces an error, since both time and velocity are the same kind of object:

time = Table[i, {i, 1, 10}]

velocity = Table[0, {i, 1, Length[time]}]

F1[t_, v_, h_] := 
Do[v[[i + 1]] = v[[i]] + t[[i]], {i, 1, Length[t] - 1}]
F1[time, velocity, 1]

F2[t_, h_] := 
Do[velocity[[i + 1]] = velocity[[i]] + t[[i]], {i, 1, Length[t] - 1}]
F2[time, 1]
velocity


Out[253]= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Out[254]= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

During evaluation of In[253]:= Set::setps: {0,0,0,0,0,0,0,0,0,0} in the part assignment is not a symbol. >>

During evaluation of In[253]:= Set::setps: {0,0,0,0,0,0,0,0,0,0} in the part assignment is not a symbol. >>

During evaluation of In[253]:= Set::setps: {0,0,0,0,0,0,0,0,0,0} in the part assignment is not a symbol. >>

During evaluation of In[253]:= General::stop: Further output of Set::setps will be suppressed during this calculation. >>

Out[259]= {0, 1, 3, 6, 10, 15, 21, 28, 36, 45}

and would be ofcourse thankful for any solutions which include keeping the more general F1 over F2.

Thank you!

dontknow
  • 13
  • 3
  • Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory Tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. – bbgodfrey Jun 05 '15 at 14:49
  • 1
    You are attempting to make an assignment to the argument of a function, which won't work as written. Take a look at this FAQ for a complete explanation and possible workarounds: Attempting to make an assignment to the argument of a function. – MarcoB Jun 05 '15 at 14:57
  • The list[[i]]= form is not usually what you want to use. Imitating FORTRAN in Mathematica is possible, but it makes solving your problem more difficult. For this kind of problem, I generally write a function that performs a single time step, something like onestep[{t_, ...}]:={t+1, ...}, and then get the answer by applying onestep to an initial condition, {0, ...} using NestList. – John Doty Jun 05 '15 at 17:26

1 Answers1

1

The problem is that the F1 substitutes its argument in the right hand side with out any hold.

Try this:

SetAttributes[F1, HoldAll];
F1[t_, v_, h_] := 
 Do[v[[i + 1]] = v[[i]] + t[[i]], {i, 1, Length[t] - 1}];
F1[time, velocity, 1];
velocity
(*{0, 1, 3, 6, 10, 15, 21, 28, 36, 45}*)

By the way, I am not sure what you are looking after but you can do this calculations as follows:

velocity[[2 ;;]] = Accumulate[time][[;; -2]];
velocity
(*{0, 1, 3, 6, 10, 15, 21, 28, 36, 45}*)
Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78