Search code examples
arraysmatlabfunctiondimensionscell-array

How to transform 'double' into 'cell array'?


My code:

B = zeros(height(A),1);
col_names = A.Properties.VariableNames; % Replicate header names 
for k = 1:height(A)
    % the following 'cellfun' compares each column to the values in A.L{k},
    % and returns a cell array of the result for each of them, then
    % 'cell2mat' converts it to logical array, and 'any' combines the
    % results for all elements in A.L{k} to one logical vector:
    C = any(cell2mat(...
        cellfun(@(x) strcmp(col_names,x),A.L{k},...
        'UniformOutput', false).'),1);
    % then a logical indexing is used to define the columns for summation:
    B(k) = sum(A{k,C});
end

generates the following error message.

Error using cellfun
Input #2 expected to be a cell array, was double instead.

How do I solve this error?

This is how table 'A' looks like: enter image description here

A.L{1,1} contains:

enter image description here


Solution

  • I'm not entirely sure quite what's going on here, but here's a fabricated example that I think is similar to what you're trying to achieve.

    %% Setup - fabricate some data
    colNames = {'xx', 'yy', 'zz', 'qq'};
    h = 20;
    % It looks like 'L' contains something related to the column names
    % so I'm going to build something like that.
    L = repmat(colNames, h, 1);
    % Empty some rows out completely
    L(rand(h,1) > 0.7, :) = {''};
    % Empty some other cells out at random
    L(rand(numel(L), 1) > 0.8) = {''};
    A = table(L, rand(h,1), rand(h, 1), rand(h, 1), rand(h, 1), ...
        'VariableNames', ['L', colNames]);
    
    %% Attempt to process each row
    varNames = A.Properties.VariableNames;
    B = zeros(height(A), 1);
    for k = 1:height(A)
        % I think this is what's required - work out which columns are
        % named in "A.L(k,:)". This can be done simply by using ISMEMBER
        % on the row of A.L.
        C = ismember(varNames, A.L(k,:));
        B(k) = sum(A{k, C});
    end
    

    If I'm completely off-course here, then perhaps you could give us an executable example.