Search code examples
arraysmatlabcell-array

How can I get a non-continuous data in a nan array organized in a cell array


I going to describe my problem, then I hope that you can help me.

I have the next numeric array in MATLAB:

A=[1 , 2 , 7 , NaN , NaN , 5.3 , NaN , 8 , 9 , 6 , 5 , 1 , 0 , NaN , NaN]; % (1x15)

Now I want to get someway the next information:

[a,b]=somefunction(A)

where:

a = {[1 2 7]; [5.3] ; [8 9 6 5 1 0]}; 
b = {1 3; 6 6 ; 8 13};

As you can see, the cell array "a" has the information of "A" without NaN values, but keeping the sequence and interpreting the NaN like a "cut" in the array.

The variable "b" has the information of the cordinates of the begining and ending of each one of the cells in the variable "a" corresponding to the vector array "A".


Solution

  • Alternative solution: matching cell format

    Code

    function [a,b]=somefunction(A)
    endindex=find(diff([isnan(A),1])==1);
    startindex=find(diff([1,isnan(A)])==-1);
    lengths=endindex-startindex+1;
    
    a=mat2cell(A(~isnan(A)).',lengths,1);
    
    b=[startindex(:),endindex(:)];
    b=mat2cell(b,ones(1,size(b,1)),ones(1,size(b,2)));
    end
    

    Output

    [a,b]=somefunction(A)
    a = 
    
        [3x1 double]
        [    5.3000]
        [6x1 double]
    
    
    b = 
    
        [1]    [ 3]
        [6]    [ 6]
        [8]    [13]