提前感谢您的帮助。我有一个大矩阵:1,000,000行和10列。我想对每一行求和并创建一个新矩阵,其中只有总和为整数的行。到目前为止,我已经尝试过这种方法,并在很多方面对它进行了操纵,但是我被卡住了。我怎么能这样做?
for k = 1:1000000
x = sum(A(k,:)) %A is my large matrix
if x-round(x,0)==0
y = [y;x]% y is my new matrix
end
end
答案 0 :(得分:1)
您可以使用for
的第二个输入,而不是使用y
循环并不断扩展x
这对于大型sum
数组来说非常慢。计算每一行的总和,然后通过使用一个非常小的epsilon比较圆形和原始版本(比较浮点数的正确方法),可以确定哪些行总和为一个整数。
% Sum each row and divide by 3
row_sums = sum(x, 2) / 3;
% Determine which of the row-wise sums are integers
sum_is_integer = abs(round(row_sums) - row_sums) < eps;
% If you want the sums that were integers
y = row_sums(sum_is_integer);
% If you want a sub-matrix containing only the rows where the sums were an integer
z = x(sum_is_integer, :);