Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MATLAB:将矩阵中的值求和到一列的阈值水平_Matlab_Multidimensional Array_Sum - Fatal编程技术网

MATLAB:将矩阵中的值求和到一列的阈值水平

MATLAB:将矩阵中的值求和到一列的阈值水平,matlab,multidimensional-array,sum,Matlab,Multidimensional Array,Sum,以一个2列5行的矩阵为例 2 1 5 1 3 1 4 1 7 1 我想做的是: 从位置1,1开始,向下移动第一列,找到导致值的单元格,您可以完全执行循环中描述的逻辑 每一行,测试最近的总和,这里的最近表示从最后一个输出行到当前行 如果总和为10或更多,则按说明添加到输出。否则继续下一行 代码: 结果: >> disp(output) 10 3 4 1 7 1 这是我建议的解决方案: % Create A and the cumulative sum o

以一个2列5行的矩阵为例

2 1
5 1
3 1
4 1
7 1
我想做的是:


从位置1,1开始,向下移动第一列,找到导致值的单元格,您可以完全执行循环中描述的逻辑

每一行,测试最近的总和,这里的最近表示从最后一个输出行到当前行

如果总和为10或更多,则按说明添加到输出。否则继续下一行

代码:

结果:

>> disp(output)
   10  3
    4  1
    7  1

这是我建议的解决方案:

% Create A and the cumulative sum of its first column...
A = [2 1; 5 1; 3 1; 4 1; 7 1];
A_cs = cumsum(A(:,1));

% Create a variable R to store the result and an indexer to it...
R = NaN(size(A_cs,1),2);
R_off = 1;

% Perform the computation...
while (~isempty(A_cs))
    idx = find(A_cs <= 10);
    idx_max = max(idx);

    R(R_off,:) = [A_cs(idx_max) sum(A(idx,2))];

    A_cs = A_cs - A_cs(idx_max);
    disp(A_cs);
    A_cs(idx) = [];

    R_off = R_off + 1;
end

% Clear unused slots in R...
R(any(isnan(R),2),:) = [];

在这种情况下,通过获取位于指定阈值10内的第一累积和组的最大索引来执行计算。一旦找到它,其相应的值将插入结果矩阵,并通过删除组条目并减去它们的和来更新累积和数组。当累积和数组为空时,迭代结束,R包含所需的结果。

如果在4和7之间的第一列中有一个2,那么输出是否预期包含6 2而不是4 1,或者像@Wolfie的答案当前包含输入矩阵中的两行一样?
% Original data
x =[2 1; 5 1; 3 1; 4 1; 7 1];
% Output for result
output = [];
% idx is the row we start sum from on each test
idx = 1;
% Loop over all rows
for ii = 1:size(x,1)
    % Get sum in column 1
    s = sum(x(idx:ii, 1));
    if s == 10
        % Append row with sums
        output = [output; 10 sum(x(idx:ii,2))];
        idx = ii+1;
    elseif s > 10
        % Append all "recent" rows
        output = [output; x(idx:ii,:)];
        idx = ii+1;
    end
end
>> disp(output)
   10  3
    4  1
    7  1
% Create A and the cumulative sum of its first column...
A = [2 1; 5 1; 3 1; 4 1; 7 1];
A_cs = cumsum(A(:,1));

% Create a variable R to store the result and an indexer to it...
R = NaN(size(A_cs,1),2);
R_off = 1;

% Perform the computation...
while (~isempty(A_cs))
    idx = find(A_cs <= 10);
    idx_max = max(idx);

    R(R_off,:) = [A_cs(idx_max) sum(A(idx,2))];

    A_cs = A_cs - A_cs(idx_max);
    disp(A_cs);
    A_cs(idx) = [];

    R_off = R_off + 1;
end

% Clear unused slots in R...
R(any(isnan(R),2),:) = [];