MATLAB: How to add a column vector to every column within a cell array

matricesmatrix array

Ok, so I now have a cell array with 1000 m*n matrices which I have fiddled with earlier.
What I now need to do is to each column within each of those m*n matrices, add a column vector 'A'
So, my m*n matrices look like:
1 2 3, 4 5 6, 7 8 9,
my column vector is
1, 2, 1,
so i want my output to be
2 3 4, 6 7 8, 8 9 10,
Again, please keep this nice and simple for me 🙂

Best Answer

T = {magic(3); ones(3); zeros(3)}; % Initial cell array.
A = [1 2 3]; % The vector to add.
Tnew = cellfun(@(x) bsxfun(@plus,x,A'),T,'Un',0 ); % or 'T ='
Now compare:
T{1},Tnew{1}
BSXFUN is a great function to get to know if you are going to be spending time with MATLAB. And since you are working with cell arrays, you should learn CELLFUN too. It is like a FOR loop in one line!