3

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?

toygan kılıç
  • 422
  • 4
  • 16

2 Answers2

3

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
Community
  • 1
  • 1
Santhan Salai
  • 3,888
  • 19
  • 29
1

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.

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52