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}];
1
  • What's wrong with a loop? Also are all your elements always the same sizes? Maybe you can use a normal array... Commented May 28, 2015 at 10:51

2 Answers 2

1

Some classic use of cellfun maybe

C=cellfun(@horzcat, A, B, 'uni', 0)
Sign up to request clarification or add additional context in comments.

5 Comments

Please note that cellfun is just a for-loop under the hood and will almost definitely not realise any performance gains...
@Dan, Please point to any claims regarding performance in my answer or requests regarding performance in the question.
stackoverflow.com/questions/18284027/…. Afterall, it's basically a for loop with extra overhead.
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, 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 stackoverflow.com/a/24752746/1292374
0

Is that possible:

B = reshape(B, [], 1);
C = [A(:) B(1:length(A))];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.