【问题标题】:How to make conditional calculations in a table using loop mechanisms?如何使用循环机制在表中进行条件计算?
【发布时间】:2016-12-31 08:50:19
【问题描述】:

我有下表('ABC'):


目标:为每个日期创建 2 个新变量(例如“LSum”和“USum”)。 'LSum' 应该计算列 Universe (4-281) 中所有单元格值的总和,但仅限于那些标题在 ABC.L 的单元格数组中的值,用于该特定日期。以同样的方式,'USum' 应该计算列中所有单元格值的总和,但仅限于那些标题在 ABC.U 的单元格数组中的值,对于该特定日期。


% load content
load ('ABC.mat'); 
% run through every date, starting from the top 
for row=1:size(ABC,1); 
% for-loop for 'L' that determines for what specific cells (of col. 4-281) the following calculation has to be done: how? 
% for-loop for 'U' that determines for what specific cells (of col. 4-281) the following calculation has to be done: how? 
% now generate new variables
LSum = sum(); % But how can I use if clause here to select only eligible cells that enter into the sum calculation? 
USum = sum(); % Same problem here as LSum
end; 

% Concatenate table ABC and the newly formed variables into 1 table
ABC = [ABC(:,1:3) LSum USum ABC(:,3+1:end)];

感谢您的帮助,尤其是同时循环遍历日期和 'L' 和 'U' 的元胞数组。


【问题讨论】:

  • 请向我们展示您已经尝试过的内容,并解释您遇到的任何困难。
  • %load content: load ('ABC.mat'); %run through each date, 从顶部开始:for row=1:size(ABC,1); %for-loop for 'L' 确定哪些特定单元格(第 4-281 列) 必须进行以下计算:如何? 'U' 的 %for-loop 确定 col 中的特定对象。 4-281 必须进行以下计算:如何? %现在生成新变量:LSum = sum(); %但是如何使用 if 子句只选择符合条件的单元格? USum = sum(); end; end; end; %将表 ABC 和新形成的变量连接到一张表中:ABC = [ABC(:,1:3) LSum USum ABC(:,3+1:end)];
  • 请编辑问题并在其中添加此代码。
  • 完成!请参阅上面的 Dev-iL 部分。谢谢

标签: matlab loops if-statement for-loop


【解决方案1】:

避免循环的可能方法是利用 rowfun() 函数。假设我们有与您类似的表格。

使用表变量名称按列扩充表。

tb = horzcat(tb,repmat({tb.Properties.VariableNames},1,height(tb))');

定义应用于每一行的函数。

function out = selectiveSum(varargin)
  [~,~,sumColsId] = intersect(varargin{2},varargin{end});
  out = sum(cell2mat(varargin(sumColsId)));
end

运行 rowfun()。

sums = rowfun(@selectiveSum,tb);

该函数只处理一个选择器数组(L 列)。添加第二个并让selectiveSum() 返回1x2 向量。

【讨论】:

  • 谢谢枫梅普森!应用 out 函数 时出现以下错误消息:“此上下文中不允许函数定义。”你知道如何缓解这个问题吗?
  • 是selectiveSum()函数,out只是输出。如果您的 Matlab 版本早于 2016b,则必须在单独的文件中定义函数。
  • 不,我使用的是 2016b 版本。错误消息仍然出现。 function out = selectiveSum(varargin) ↑ Error: Function definitions are not permitted in this context.
  • 好的,你有没有尝试将selectiveSum() 函数保存到单独的文件selectiveSum.m 中,然后调用sums = rowfun(@selectiveSum,tb); ?上面提供的函数定义具有有效的语法。
  • 我已经单独保存了。尽管如此,它不起作用:我现在附上了上面的错误消息,以便您查看。感谢您再次调查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2012-11-05
相关资源
最近更新 更多