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.
Here’s a loop solution and a
repmatsolution.% Define some example data.
Edit:
aandbare column vectors, not row vectors.b = [ 6:10 ]';%5:10has vertical size of 6, not 5, so to match the question6:10is used.First, the very basic loop solution: loop through all
aIndex,bIndexpairs, subtract the difference of elements addressed byaIndexandbIndexand store the result inLoopDifferenceMatrix(aIndex, bIndex).This is an alternative
repmatsolution. Replicateahorizontally by usingrepmatso that its horizontal size matchessize(b,1)(the horizontal size ofb). Then replicate transposedbvertically by usingrepmatso that its vertical size matchessize(a,1)(the original horizontal size ofa). Subtract replicatedafrom replicatedband store the result inDifferenceMatrix.