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.

This question already has an answer here:

I'd like to write a function, that would take a matrix as an input parameter and would change it by multiplying one of its rows by a factor.

I try to do it in the following way:

matrix=Table[i*j,{i,Range@2},{j,Range@2}]
MultiplyRowByFactor[m_,factor_,iRow_]:=Module[{},m[[All,iRow]]*=factor;m]
MultiplyRowByFactor[matrix,2,1]

and get an error message

Set::setps: "{{1,2},{2,4}} in the part assignment is not a symbol. "

Of course, if I change the matrix outside of the function:

matrix[[All,1]]*=2;
matrix

everything works as expected.

What is the problem and how can I write a function to modify a matrix "in place"?

share|improve this question

marked as duplicate by Kuba, m_goldberg, Szabolcs, Yves Klett, Simon Woods Apr 28 at 20:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
You need to set HoldFirst attribute for your function. Also, do not use Module if you are not going to scope anything, it will only slow you down. –  Kuba Apr 28 at 18:10
    
@Kuba, thank you for the comment and for the links. –  user1541776 Apr 28 at 23:55

1 Answer 1

up vote 3 down vote accepted

To prevent m from evaluating to its value, use the following command:

SetAttributes[MultiplyRowByFactor, HoldFirst];

Just once, right after the declaration of MultiplyRowByFactor. Now the first argument of this function, which is just m, is held, and everything works.

share|improve this answer

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