2
$\begingroup$

I have list of stock data as follows:

lis1= 
{{{1992/10/12, 126.946, AEX}, {1992/10/13, 127.85, AEX}},
 {{1992/10/12, 88.487, AFLI},{1992/10/13, 91.825, AFLI}}}

I would like to replace the closing prive (second entry in each nested list) with the corresponding value of the following list. Both lists have the same lengths.

lis2=
{{125.12,125.32},{91.34,91.88}}

Does anyone have a hint?

$\endgroup$
  • $\begingroup$ Possible duplicate: (3069) $\endgroup$ – Mr.Wizard Apr 24 '15 at 16:42
4
$\begingroup$

For in-place modification use assignment to Part:

lis1[[All, All, 2]] = lis2;

lis1
{{{83/5, 125.12, AEX}, {996/65, 125.32, AEX}},
 {{83/5, 91.34, AFLI}, {996/65, 91.88,  AFLI}}}

If you do not want to modify lis1 make a copy first and use the same syntax.


Automation of the copy operation:

(newPart[expr_, part___] = new_) ^:= Module[{x = expr}, x[[part]] = new; x]

(Syntax highlighting may complain but the definition still works.)

Usage example:

(* starting with original lis1 definition *)

newPart[lis1, All, All, 2] = lis2
{{{83/5, 125.12, AEX}, {996/65, 125.32, AEX}},
 {{83/5, 91.34, AFLI}, {996/65, 91.88, AFLI}}}

lis1 remains unchanged:

lis1
{{{83/5, 126.946, AEX}, {996/65, 127.85, AEX}},
 {{83/5, 88.487, AFLI}, {996/65, 91.825, AFLI}}}
$\endgroup$
  • $\begingroup$ is there an elegant way to do that without making a copy? $\endgroup$ – garej Aug 4 '15 at 14:23
  • $\begingroup$ @garej In my opinion making a copy is the best approach. It is easy to write a utility function to automate this; I'll append that to my answer for your consideration. $\endgroup$ – Mr.Wizard Aug 4 '15 at 18:34
  • $\begingroup$ thank you, I see. In my case I have a matrix, (re)generated by random process (in Dynamic setting). Is it fine to make a copy of it as it changes each time something else changes? $\endgroup$ – garej Aug 5 '15 at 9:02
  • $\begingroup$ @garej In your position I would try it and see. I think memory management and garbage collection should allow that to work. The way you describe that however it sounds like you could use in-place modification. I wonder what the need for a copy with every change is? $\endgroup$ – Mr.Wizard Aug 6 '15 at 4:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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