【问题标题】:How to make calculations on certain cells (within a table) that meet specific criteria?如何对满足特定条件的某些单元格(表格内)进行计算?
【发布时间】:2017-05-19 01:43:00
【问题描述】:

我有以下代码:

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

这是我的桌子:

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


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


红色箭头:sum 函数引用的是什么(同一日期的 L)。

绿色箭头:我现在要参考的内容(上一个日期的 L)。

感谢您的帮助

【问题讨论】:

  • cellfun和find的组合?
  • 你能写出ABC.L的值吗?
  • 是的。请参阅上面的快照,@MendiBarel!
  • 你最好看看“varfun”和“rowfun”函数。
  • 上述示例的代码是什么样子的,在进行计算之前,我如何(&在哪里)先将条件整合到 ABC.L 中?谢谢

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


【解决方案1】:

为此,您需要先提取要求和的列,然后对它们求和:

% 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

【讨论】:

  • 感谢@EBH 的全面帮助!它运行顺利
  • @John,欢迎您(并为这个棘手的问题投了赞成票……)
  • 我再次:运行代码时,我检测到弹出以下错误消息:“错误使用 cellfun 输入 #2 应为元胞数组,而不是双倍。”有没有简单的方法来修复它? 谢谢
  • @John 通常表示ABC.L{k} 不是元胞数组,您确定ABC 中的数据与您在问题中写的一样吗?
  • @John,如果你想提取下一行的列,你应该写strcmp(col_names,x),ABC.L{k+1} 并在height(ABC)-1 中结束循环。此外,您必须考虑在最后一行求和的列(即,当没有下一行可提取时)。
【解决方案2】:

一般而言,在 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-05
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多