Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB equating cell elements to array

Tags:

cell

matlab

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?

like image 693
toygan kılıç Avatar asked Mar 02 '26 13:03

toygan kılıç


1 Answers

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
like image 72
Santhan Salai Avatar answered Mar 05 '26 05:03

Santhan Salai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!