2
votes

I'm trying to vectorize the following code in Matlab. I've never had to vectorize with a matrix involved. Doing some research it seems I should use bsxfun but I'm having a hard trying to understand how it works in my example. I've tried a few things but can't seem to figure it out. Below is the non-vectorized code that runs and produces the output I want.

# W is 500 x 100 matrix
# delta is 100 x 1 vector
# alpha is scalar

for i = 1: 100
    W(:,i) = W(:, i) - (alpha * delta(i));
end

Any help is appreciated! Thanks.

1

1 Answers

2
votes

Easy with bsxfun:

W = bsxfun(@minus, W, alpha*delta.');

This works as follows: delta is transformed into a row vector (.') and multiplied by the scalar alpha. The obtained row vector is subtracted from each row of W using bsxfun. You can view bsxfun as an "implicit repmat": it replicates the row alpha*Delta.' as many times as needed to match the size of W; and then it does the subtraction (@minus).