The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: Pointwise multiplication of matrix with vector
Replies: 7   Last Post: Jul 28, 2014 11:36 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]

Posts: 1
Registered: 1/27/06
Pointwise multiplication of matrix with vector
Posted: Jan 27, 2006 8:58 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply


In Matlab one can write
c = 3; % (some scalar)
x = 0:10; % (some vector)
y = c * x; % (multiply every component of x with c)

This is much faster than using a for loop and writing
for k = 1:length(x)
y(k) = c * x(k);

I would now like to do a similar thing, but where the scalar is
replaced by a n x 1 vector and the vector is replaced by a n x m
matrix. I.e., I would like to multiply each column of a matrix
pointwise with a column vector.

So far I can see two solutions for this (besides a double for loop):

1. Use repmat to create m copies of the colum vector and multiply the
resulting matrix pointwise with the original matrix:

% Given a vector v (n x 1) and matrix A (n x m):
V = repmat(v, 1, m);
B = A .* V;

2. Use a for loop to go through each element of the vector and thus
reduce to the problem to the <scalar> * <vector>

for k = 1:length(v)
B(1, :) = A(1, :) * v(k);

I have found the second solution to be faster than the first one. Is
there a better solution?


Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2017. All Rights Reserved.