如何将'double'转换为'cell array'?

时间:2017-01-09 10:08:54

标签: arrays matlab function dimensions cell-array

我的代码:

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

生成以下错误消息。

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

如何解决此错误?

这就是表'A'的样子: enter image description here

A.L {1,1}包含:

enter image description here

2 个答案:

答案 0 :(得分:1)

C = any(cell2mat(...
    cellfun(@(x) strcmp(col_names,x),A.L{k},...
    'UniformOutput', false).'),1);

此处A.L{k}获取位于A.L第k个位置的单元格内容。使用A.L(k),您将获得位于A.L

的单元格
tmp = A.L(k);
C = any(cell2mat(...
    cellfun(@(x) strcmp(col_names,x),tmp{1},...
    'UniformOutput', false).'),1);

有点像hacky方式,因为你首先需要获取A.L(k)然后的单元格需要该单元格的内容,所以你需要一个临时变量。

答案 1 :(得分:0)

我并不完全确定这里发生了什么,但这里有一个我认为类似于你正在努力尝试的例子。实现

%% 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

如果我完全偏离这里,那么也许你可以给我们一个可执行的例子。