Increase the value in Matlab to the second value (logic 1: n)

I have a 2 year column in Matlab as shown below:

             % Col2 Is always greater than Col1
mat  = [2009 2012 ;
        2012 2012 ;
        2012 2013 ;

I need to do 2009: 2012 for row1, 2012: 2012 for row2, etc ... This is not very simple, since the size 1: N continues to change for each pair.

FinalAns = [    2009
                2010
                2011
                2012           % -- 
                2012           % -- 
                2012
                2013      ] ;  % -- 

I cannot use the 'for' loop, because the data size is very large, and I could not use it for this accumarray. A vectorized solution would be highly appreciated.

+3
source share
3 answers

This does what you need:

n = size(mat, 1);
c = arrayfun(@(x) {mat(x, 1):mat(x, 2)}, 1:n);
FinalAns = [c{:}];
+2
source

You can easily use arrayfun to create a matrix of cells as follows:

>> Cells = arrayfun(@(a, b) {a:b}, Col1, Col2);
>> Cells{1}

ans =

        2009        2010        2011        2012

>> Cells{2}

ans =

        2012

>> Cells{3}

ans =

        2012        2013

, , , , :

>> horzcat(Cells{:})

ans =

        2009        2010        2011        2012        2012        2012        2013
+2

This will work:

Col1 = [ 2009  ; 2012 ; 2012 ] ;
Col2 = [ 2012  ; 2012 ; 2013 ] ;

finalAnswer = zeros(sum(Col2 - Col1) + length(Col1),1);

curr=0;
for iter = 1:length(Col1)
    finalAnswer((curr+1):(curr + Col2(iter)-Col1(iter)+1)) = Col1(iter):Col2(iter);
    curr = curr + Col2(iter)-Col1(iter)+1;
end

There is still a for loop, but with a prior allocation finalAnswer, as mentioned above, you should get most of the winnings that you expect from a vectorized solution.

+1
source

All Articles