如何在符合特定标准的某些单元格(表格内)上进行计算?

时间:2017-01-04 17:00:13

标签: matlab for-loop cell-array matlab-table

我有以下代码:

L_sum = zeros(height(ABC),1);
for i = 1:height(ABC)
     L_sum(i) = sum(ABC{i, ABC.L(i,4:281)});
 end

这是我的表: enter image description here

问题:我的sum函数对每个日期的整行值(col.4-281)求和,而我只想要添加其标题在ABC的单元格数组中的那些单元格.L ,对于任何给定的日期。

X = ABC.L {1,1};给出(摘录):

enter image description here

红色箭头:引用的和函数(相同日期的L)。

绿色箭头:我现在想要引用的内容(上一个日期的L)。 enter image description here

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

通常,在matlab中,您不需要使用for循环来执行简单的操作,如选择性求和。 例如:

Data=...
    [1 2 3;
    4 5 6;
    7 8 9;
    7 7 7];

NofRows=size(Data,1);
RowsToSum=3:NofRows;
ColToSum=[1,3];
% sum second dimension 2d array
Result=sum(Data(RowsToSum,ColToSum), 2)

% table mode
DataTable=array2table(Data);
Result2=sum(DataTable{RowsToSum,ColToSum}, 2)

答案 1 :(得分:0)

要做到这一点,你需要首先提取你想要求和的列,然后求它们:

% some arbitrary data:
ABC = table;
ABC.L{1,1} = {'aa','cc'};
ABC.L{2,1} = {'aa','b'};
ABC.L{3,1} = {'aa','d'};
ABC.L{4,1} = {'b','d'};
ABC{1:4,2:5} = magic(4);
ABC.Properties.VariableNames(2:5) = {'aa','b','cc','d'}

% summing the correct columns:
L_sum = zeros(height(ABC),1);
col_names = ABC.Properties.VariableNames; % just to make things shorter
for k = 1:height(ABC)
    % the following 'cellfun' compares each column to the values in ABC.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 ABC.L{k} to one logical vector:
    col_to_sum = any(cell2mat(...
        cellfun(@(x) strcmp(col_names,x),ABC.L{k},...
        'UniformOutput', false).'),1);
    % then a logical indexing is used to define the columns for summation:
    L_sum(k) = sum(ABC{k,col_to_sum});
end