MATLAB equating cell elements to array

149 Views Asked by At

I'm trying to equate each element to an array which correspond to cell element. To explain it more precisely, e.g

A    = {[1 1 1], [0 0 0 0 0], [1 1],[0 0 0 0 0]};
B    = [0 1 0 0];

So the thing I want is :

A= {[0 0 0],[1 1 1 1 1],[0 0],[0 0 0 0 0]};

Possible solution with for loop is :

for ii=1:length(A)
     A{ii}(:)=B(ii);
end

Is there any methode which does not use loop?

2

There are 2 best solutions below

0
On BEST ANSWER

Using repelem and mat2cell

lens = cellfun(@numel, A);

out = mat2cell(repelem(B,lens).*ones(1,sum(lens)),1,lens)

Note:

  1. cellfun is looping in disguise. But, here cellfun is used to find the number of elements alone. So this could be considered almost vectorised :P
  2. repelem function is introduced in R2015a. You may not be able to run this in prior versions. Instead you may create your own custom repelem function. Refer this answer
0
On

You can do it like this:

A=cellfun(@(x, y) repmat(y, size(x)), A, num2cell(B), 'uni', 0)

This has the advantage that it handles matrices of any size or dimension in A. No assumption on being vector.