0

How to insert elements of a cell array into another cell array without a for loop? The elements of the cell A are all integers.

Input:

A = [1x2 double]    [1x2 double]    
    [1x2 double]    [1x2 double]   
    [1x2 double]    [1x2 double]    
    [1x2 double]    [1x2 double]    
    [1x2 double]    [1x2 double]    
    [1x2 double]    [1x2 double]

A{1}=[2 5]
A{2}=[6 8]

B=[8]    [7]   
  [7]    [0]    
  [4]    [3]   
  [7]    [0]    
  [2]    [1]   
  [1]    [2]

C=cell(6,2);

Output:

C{1}=[A{1} B{1}];
C{2}=[A{2} B{2}];
Dan
  • 45,079
  • 17
  • 88
  • 157
  • What's wrong with a loop? Also are all your elements always the same sizes? Maybe you can use a normal array... – Dan May 28 '15 at 10:51

2 Answers2

1

Some classic use of cellfun maybe

C=cellfun(@horzcat, A, B, 'uni', 0)
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
  • Please note that `cellfun` is just a for-loop under the hood and will almost definitely not realise any performance gains... – Dan May 28 '15 at 10:50
  • @Dan, Please point to any claims regarding performance in my answer or requests regarding performance in the question. – Mohsen Nosratinia May 28 '15 at 10:52
  • http://stackoverflow.com/questions/18284027/cellfun-versus-simple-matlab-loop-performance. Afterall, it's basically a for loop with extra overhead. – Dan May 28 '15 at 10:54
  • 1
    As for request regarding performance in the question, it's pretty fair to assume that anyone saying they don't want for-loops are doing so because they believe they will get a performance boost. So I think it's worth adding a warning that `cellfun` is unlikely to give you the performance boost that vectorization often can because `cellfun` is not a vectorized solution even though it looks like one. – Dan May 28 '15 at 11:04
  • @Dan, It depends on your priorities. I prefer a readable code to an optimized one until I see there is a need for optimization. Additionally, I can't say for sure that for loop **always** outperforms `cellfun` just because of some profiling on a specific case. You may need to try it in your specific problem. Also there is the question of MathWorks's changes in their implementation in future versions which can make `cellfun` faster or on par with for-loop. Similar discussion occurred here before http://stackoverflow.com/a/24752746/1292374 – Mohsen Nosratinia May 28 '15 at 11:39
0

Is that possible:

B = reshape(B, [], 1);
C = [A(:) B(1:length(A))];
scmg
  • 1,904
  • 1
  • 15
  • 24