i scoured the intertubes for over an hour to find an answer to the following query, but to no avail. no basic matlab tutorial sites seem to have an answer… eventually, i just broke down and asked a pro, who had a one-word answer. here is my expansion of that one-hand-clapping answer:

QUESTION
how do i add or subtract two matrices of different dimensions?

ANSWER
use the tiling/replicating function repmat to get them to be the required dimensions.

for example, i have a 2×1 matrix A and a 2×100 matrix B. i wish to add them (or subtract them):

> > result = A + B

normally, i would get a message complaining that “matrix dimensions must be the same”. and i could hack around this by splitting my 2×1 matrix into two scalars and dealing with the addition row-by-row. hardly a scalable solution. with repmat, the solution is simple:

> > result = repmat(A, 1, 100) + B           %tile A 1 time vertically and 100 times horizontally

done.

__________

code used:

>> Q

Q =

4     4     4     4     4
5     5     5     5     5

>> P

P =

2
1

>> P+Q
??? Error using ==> plus
Matrix dimensions must agree.

>> repmat(P, 1, 5) + Q

ans =

6     6     6     6     6
6     6     6     6     6

\m/

Advertisements