# matlab matrices of different sizes (indexing, for loop, and bsxfun)

I have two matrices of different sizes. Let's just define matrix {a} as a(1:10) <10 x 1> and matrix {b} as b(6:10) <5 x 1>. I need a for loop or equivalent (bsxfun) which gets the difference between matrix {a} and {b}, the code will iterate based on the size of matrix {b}. For example, the first value of matrix {a} is 1, the code will get the difference of all of matrix {b} values. So, it will run a total of 5 times. The next value of matrix {a} is 2, the code will iterate 5 times. The code will iterate until the end of matrix {a} which is value 10.

If you can could you write both a for loop without bsxfun and one with and explain how you indexed the values. Also, just for my edification, instead of two matrices, how would the code change if there were N matrices (N>2)?

Thank you.

## Answers

Here's a loop solution and a repmat solution.

% Define some example data.

**Edit:** a and b are column vectors, not row vectors.

a = [ 1:10 ]';

b = [ 6:10 ]'; % 5:10 has vertical size of 6, not 5, so to match the question 6:10 is used.

First, the very basic loop solution: loop through all aIndex,bIndex pairs, subtract the difference of elements addressed by aIndex and bIndex and store the result in LoopDifferenceMatrix(aIndex, bIndex).

for aIndex = 1:size(a,1) for bIndex = 1:size(b,1) LoopDifferenceMatrix(aIndex, bIndex) = a(aIndex) - b(bIndex); end end

This is an alternative repmat solution. Replicate a horizontally by using repmat so that its horizontal size matches size(b,1) (the horizontal size of b). Then replicate transposed b vertically by using repmat so that its vertical size matches size(a,1) (the original horizontal size of a). Subtract replicated a from replicated b and store the result in DifferenceMatrix.

DifferenceMatrix = repmat(a, 1, size(b,1)) - repmat(b', size(a,1), 1); DifferenceMatrix = -5 -6 -7 -8 -9 -4 -5 -6 -7 -8 -3 -4 -5 -6 -7 -2 -3 -4 -5 -6 -1 -2 -3 -4 -5 0 -1 -2 -3 -4 1 0 -1 -2 -3 2 1 0 -1 -2 3 2 1 0 -1 4 3 2 1 0 isequal(DifferenceMatrix, LoopDifferenceMatrix) ans = 1

Is this what you're trying to do?

a = 1:10; b = 6:10; c = zeros(length(b),length(a)); d = zeros(length(b),length(a)); for n = 1:length(b) c(n,:) = bsxfun(@minus,a,b(n)); d(n,:) = a - b(n); end

As for how to do it with N matrices you would have to specify what you want to do with the N'th matrix.