问题描述:

I have N by M matrix A , a 1 by M matrix or a row vector B

and another 1 by M row vector C. Can I vectorize the following code more than that?

`for i = 1:N`

A(i,:) = (A(i,:)-B)./C;

end;

and what about more general case where we have K by M matrices(K divisible by N) instead of vectors

This is what `bsxfun`

was designed to do:

```
A = bsxfun(@rdivide,bsxfun(@minus,A,B),C);
```

It will automatically expand the arrays of size `[1 M]`

to be compatible with the one of size `[N M]`

, then perform the necessary array operations on them, returning an array of size `[N M]`

.

If your `B`

and `C`

arrays are of size `[K M]`

, then it's a bit more difficult. You didn't specify what the output should be shaped, but in the most general case you can compute "(A-B)/C" for every row of `B`

and `C`

and collect these matrices in an array of size `[K N M]`

:

```
A = bsxfun(@rdivide,bsxfun(@minus,permute(A,[3 1 2]),permute(B,[1 3 2])),permute(C,[1 3 2]));
```

where `A`

is transformed to an array of size `[1 N M]`

, and both `B`

and `C`

are transformed to size `[K 1 M]`

. Depending on the size of your arrays along the various dimensions, you might benefit from putting `M`

in front (since that's the dimension along which you're subtracting, but I'm not sure.

Unless you need raw speed, I would prefer a more explicit approach:

```
N = size(A, 1);
easy = (A-repmat(B, N, 1)) ./ repmat(C, N, 1);
```

`repmat`

copies the first argument, the number of second argument times vertically (in rows), and they number of third argument times in columns. So, in this case, B is turned into N x M by replicating the vector N times vertically only.

For the more general case, where B & C are K x M, and N/K is an integer:

```
rowReps = size(A, 1)/size(B, 1);
notMuchHarder= (A - repmat(B, rowReps , 1) ./ repmat(C, rowReps, 1);
```