Search code examples
matlabmatrixcell-array

select entries and put in a matrix without loop


I have the following:

   b = [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]

whose dimensions are variable.

b{1}

ans =

 0     0     0     0

I want to put the first entry of each of the 10 vectors as the first column of matrix A

2nd column of matrix A will be as v the 1st entry of each of the 10 vectors of r:

r = 

[1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]    [1x4 double]

r{1} --> ans = 10 10 10 10

This is what i need to get:

A = 

    v{1}(1)   r{1}(1)
    v{2}(1)   r{2}(1)
    v{3}(1)   r{3}(1)

How to do that without a loop is there a way?


Solution

  • Some example data:

    b = {[ 101:104 ], [ 201:204 ], [ 301:304 ], [ 401:404 ], [ 501:504 ], [ 601:604 ], [ 701:704 ], [ 801:804 ], [ 901:904 ], [ 1001:1004 ]};
    
    r = {[ 2101:2104 ], [ 2201:2204 ], [ 2301:2304 ], [ 2401:2404 ], [ 2501:2504 ], [ 2601:2604 ], [ 2701:2704 ], [ 2801:2804 ], [ 2901:2904 ], [ 3001:3004 ]};
    

    Edit: a lot faster solution without looping by using vertcat. Edit: corrected a typo in code.

    bMatrix = vertcat(b{:});
    rMatrix = vertcat(r{:});
    A = [ bMatrix(:,1), rMatrix(:,1) ];
    

    A lot slower solution by using cellfun (cellfun does loop) :

    A = [ cellfun(@(x) x(1), b)', cellfun(@(x) x(1), r)' ];
    

    Or in parts:

    ColumnOneOfMatrixA = cellfun(@(x) x(1), b)';
    ColumnTwoOfMatrixA = cellfun(@(x) x(1), r)';
    A = [ ColumnOneOfMatrixA, ColumnTwoOfMatrixA ];
    

    Both ways give the same result.

    A =
         101        2101
         201        2201
         301        2301
         401        2401
         501        2501
         601        2601
         701        2701
         801        2801
         901        2901
        1001        3001