Reputation: 760
I would like to vectorize the calculation of the sum
A{1} + A{2} + ... + A{end}
where A
is a vector cell array and each A{i} is a nxn numeric matrix.
There are many ways to code my way through this but I was wondering if there was a clever one fitting in just one or two lines of code.
Upvotes: 1
Views: 86
Reputation: 74930
You can catenate first, then sum up along the 3rd dimension:
[A{1:3}] = deal(ones(4)); %# each element of the cell array contains a 4-by-4 array of ones
out = sum( cat(3,A{:}), 3); %# catenate, then sum
Upvotes: 4