MATLAB Answers

Dan Ryan

Linear combination of cell arrays

Asked by Dan Ryan
on 25 Jan 2013

Is there a compact way (without loops) to take linear combinations of cell arrays that contain the same type of data (matrices of various sizes) in each index of the cell array?

For example:

A = {rand(2, 2), ones(1, 2)}
B = {rand(2, 2), [3, 4]}

and I want a cell array, C, such that

C = 3*A + 4*B

I want to be able to handle a cell array of arbitrary length. I can do this with a for loop, but I was thinking that there must be a better way.


Log in to comment.


No products are associated with this question.

1 Answer

Answer by Peter Perkins
on 25 Jan 2013
 Accepted answer

Either of these will work:

>> A = {rand(2, 2), ones(1, 2)}
>> B = {rand(2, 2), [3, 4]}
>> cellfun(@(a,b) 3*a + 4*b, A, B, 'UniformOutput',false)
ans = 
    [2x2 double]    [1x2 double]
>> arrayfun(@(a,b) {3*a{:} + 4*b{:}}, A, B)
ans = 
    [2x2 double]    [1x2 double]

Whether or not this is faster or more readable than a loop is another question. Hope this helps.


Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!