首先,让我用它在做什么来注释你的代码:
% This creates a list of numbers, 1 through 100 inclusive
loop = 1:100;
% This generates a 100x100 random matrix drawn from a normal distribution
% with mean 0 and standard deviation 25
RandomNumbers = normrnd(0, 25, [100, 100]);
NumberCounter = 0;
for i = 1:10000
% This loop only runs over i from 1 to 10000, so i>=1 is always true.
% This if statement is unnecessary.
if i >= 1
% Remember that loop is a _list_ of numbers: RandomNumbers(loop, 100)
% is the whole 100th column of your random matrix, and so
% RandomNumbers(loop, 100)>25 is a _list_ of 100 boolean values,
% corresponding to whether each element of the 100th column of your matrix
% is greater than 25. By default, Matlab only treats a list of values as
% true if they are _all_ true, so this if-statement almost never evaluates
% to true.
if (RandomNumbers(loop, 100) > 25)
NumberCounter = NumberCounter + 1
% This test is doing the same thing, but testing the 100th row, instead of
% the 100th column.
elseif (RandomNumbers(100, loop) > 25)
NumberCounter = NumberCounter + 1
end
end
end
您尝试执行的正确代码是:
RandomNumbers = normrnd(0, 25, [100, 100]);
NumberCounter = 0;
for i = 1:size(RandomNumbers,1)
for j = 1:size(RandomNumbers,2)
if RandomNumbers(i,j) > 25
NumberCounter = NumberCounter + 1;
end
end
end
让我还要提一下,一种更快、更简洁的方法来做你想做的事情如下:
RandomNumbers = normrnd(0, 25, [100, 100]);
flatVersion = RandomNumbers(:);
NumberCounter = sum(flatVersion > 25);
之所以有效,是因为RandomNumbers(:)
将矩阵展开为单个向量,并且因为sum
每个真值计数为 1,每个假值计数为 0。