4
$\begingroup$

I am new to mathematica. Could you pls help me on how to write this:

I have a $5\times 10$ matrix, for example,

ap = ConstantArray[0.001, {5, 10}]

I have the second matrix $1\times 10$, for example,

b = {0.001,0.005,0.009,0.01,0.03,0.05,0.082,0.1,0.5,1}

I have a nested list z = {{1,3},{2,2},{5,7}} for position.

I would like to have this result: In first matrix ap, for each row, for example row 1, if the element position is equal or larger than the second element in list Z in case the row number matches the first element (for example here it is 3), for every element in row 1 and after position 3 (include position 3), I would like to substitute elements in ap with elements from b, here would be substitute with {0.009,0.01,0.03,0.05,0.082,0.1,0.5,1}

Similarly for row 2 in matrix ap, I would like to substitute with elements in b starting position 2. So the final matrix is:

0.001,0.001,0.009,0.01,0.03,0.05,0.082,0.1,0.5,1

0.001,0.005,0.009,0.01,0.03,0.05,0.082,0.1,0.5,1

0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001
0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001

0.001,0.001,0.001,0.001,0.001,0.001,0.082,0.1,0.5,1

Thank you very much!

$\endgroup$

3 Answers 3

6
$\begingroup$

Here's one way:

ap = ConstantArray[0.001, {5, 10}];
b = {0.001, 0.005, 0.009, 0.01, 0.03, 0.05, 0.082, 0.1, 0.5, 1};
z = {{1, 3}, {2, 2}, {5, 7}};

f[ap_, {z1_, z2_}] := ReplacePart[ap, {z1, i_ /; i >= z2} :> b[[i]]]

Fold[f, ap, z]

(* {{0.001, 0.001, 0.009, 0.01, 0.03, 0.05, 0.082, 0.1, 0.5, 1},
    {0.001, 0.005, 0.009, 0.01, 0.03, 0.05, 0.082, 0.1, 0.5, 1},
    {0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001},
    {0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001},
    {0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.082, 0.1, 0.5, 1}} *)
$\endgroup$
2
  • $\begingroup$ A rather more elegant solution than mine, though maybe more difficult to understand for someone new to Mathematica. $\endgroup$
    – Feyre
    Jun 24, 2016 at 17:15
  • $\begingroup$ This was what I was going to propose. +1. $\endgroup$ Jun 24, 2016 at 17:19
3
$\begingroup$
Table[Table[ap[[z[[i, 1]], j]] = b[[j]], {j, z[[i, 2]], 10}], {i, 3}];
ap

{{0.001, 0.001, 0.009, 0.01, 0.03, 0.05, 0.082, 0.1, 0.5, 1},

{0.001, 0.005, 0.009, 0.01, 0.03, 0.05, 0.082, 0.1, 0.5, 1},

{0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001},

{0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001},

{0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.082, 0.1, 0.5, 1}}

$\endgroup$
1
$\begingroup$
ClearAll[f]
f = Module[{m = #, r = #2, x = #3}, (m[[#, #2 ;;]] = r[[#2 ;;]]) & @@@x; m] &; 

f[ap, b, z]

Mathematica graphics

$\endgroup$

Your Answer

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

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