2
$\begingroup$

I have a list and I want to replace all rows that are given by index pos with rows from different list. But the rows in different list are sequential while the rows in the original list that need to be replaced are not. So I have:

pos = {2, 3, 5};
tbl = Table[RandomReal[], {i, 6}, {j, 3}]
newR = {{1, 1, 0}, {0, 0, 1}, {1, 1, 1}};
(tbl[[pos[[#]]]] = newR[[#]]) & /@ Range[Length[pos]];
tbl

Is there a better way to achieve that (the 4th line)? I do not like the indexing tbl[[pos[[#]]]], so I was thinking whether it would be better with let's say tbl[[#]]=... but then I do not know how to access newR.

$\endgroup$

3 Answers 3

6
$\begingroup$

You just need

tbl[[pos]] = newR;
tbl
$\endgroup$
2
$\begingroup$

If you want to keep your original matrix you might use ReplacePart

tbl = Round[#, 0.01] & @ RandomReal[1, {6, 3}];
pos = {2, 3, 5};
rep = {{1, 1, 0}, {0, 0, 1}, {1, 1, 1}};

rul = Thread[Rule[pos, rep]]

enter image description here

new = ReplacePart[tbl, rul];

{tbl, new} // MatrixForm

enter image description here

For large matrices ReplacePart is faster than copying tbl to a new matrix and then use new[[pos]] = rep.

$\endgroup$
0
$\begingroup$

Answer:

(*Generate table*)        
table = Table[RandomReal[], {6}, {3}];  

(*Declare positions*)  
pos = {2, 3, 5};


(*Rows to be used in replacement*)  
rows = {{1, 1, 0}, {0, 0, 1}, {1, 1, 1}};

(*Operation*)  
ReplacePart[table, #] &[Table[pos[[i]] -> rows[[i]], {i, Length@pos}]]

Output:

Before operation

{{0.176331, 0.81517, 0.774912}, {0.525414, 0.837054, 0.0477762}, {0.789959, 0.330025, 0.107919}, {0.259074, 0.148187, 0.462424}, {0.614598, 0.0351278, 0.443029}, {0.319434, 0.714214, 0.636573}}

After operation

{{0.176331, 0.81517, 0.774912}, {1, 1, 0}, {0, 0, 1}, {0.259074, 0.148187, 0.462424}, {1, 1, 1}, {0.319434, 0.714214, 0.636573}}

Reference:

Table
ReplacePart
Length
@ | # | etc.

$\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.