Search code examples
matlabmatrixvectorcomparecell

MATLAB: If this value of 5x5 cell with vectors [106x1] are different to zeroes,count them e put the count in a matrix


I have matchcounts (5x5)cell, every cell has a vector of double [106x1]. The vectors of double have zeros and non zero values. I want to find non zero values for every cell, count them and put the result in a matrix. I tried with this code:

a{i,j}(k,1)=[];

for k=1:106

    for i=1:5
        for j=1:5
            if (matchcounts{i,j}(k,1))~=0
                a{i,j}=a{i,j}(k,1)+1;
            end
        end
    end 
end

and others but it's not correct! Can you help me? Thanks


Solution

  • While it is possible to fix your answer above, I recommend to change the data structure to have a much simpler solution possible. Instead of having a 2D cell array which holds 1D data, choose a single 3D data structure.

    For an optimal solution you would change your previous code code to directly write the 3D-matrix, instead of converting it. To get started, this code converts it so you can already see how the data structure should look like:

    %convert to matrix
    for idx=1:numel(matchcounts)
        matchcounts{idx}=permute(matchcounts{idx},[3,2,1]);
    end
    matchcounts=cell2mat(matchcounts);
    

    And finding the nonzero elements:

    a=(matchcounts~=0)
    

    To index the result, instead of a{k,l}(m,1) you use a(k,l,m)

    To give you some rule to avoid complicated data structures in the future. Use cell arrays only for string data and data of different size. Whenever you have a cell array which contains only vectors or matrices of the same size, it should be a multidimensional matrix.