element-wise operator to scale rows of matrix with entries of a vector

17 views (last 30 days)
Given a matrix and a vector
A = [2 3 4 5;5 4 3 2;1 2 3 4;4 3 2 1];
d = [1 2 3 4];
I want to scale the rows of A with the corresponding entries of d to obtain
res = [2 3 4 5;10 8 6 4;3 6 9 12;16 12 8 4];
I figured out that
res=A.*d(:); --> correct
res2=A.*d; --> wrong, results in column-wise scaling
I know that .* indicates element-wise operations and d(:) re-shapes d into a column-vector, but my question is how to systematically read the expression A.*d(:) . Also, applies the element-wise operator .* to its left argument (here, A) or to its right argument (here, d)?

Accepted Answer

Matt J
Matt J on 17 Jan 2023
Edited: Matt J on 17 Jan 2023
Also, applies the element-wise operator .* to its left argument (here, A) or to its right argument (here, d)?
.* has two operands A and d, so it applies to both of them. It is also commutative (as you would expect), so you could have also done,
res=d(:).*A
  2 Comments
SA-W
SA-W on 17 Jan 2023
Edited: SA-W on 17 Jan 2023
Nice to know these properties.
If the element-wise operator .* has two operands, the elements of the left and right operand are somehow defined. Here, the elements of d are simply the entries, but an element of A could be a row, a column, or a individual entry...I think my question boils down to the following: Given the expression
res=d(:).*A
, how do I know that this expression scales the rows of A?
Matt J
Matt J on 17 Jan 2023
Edited: Matt J on 17 Jan 2023
how do I know that this expression scales the rows of A?
Because of Matlab's implicit expansion rules:
So, because d(:) has 1 column and A has N columns, the elements of d(:) get duplicated to form multiple columns before the multiplication is done.

Sign in to comment.

More Answers (0)

Categories

Find more on Exponents and Logarithms in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!