首先,讓我用它做什麼註釋代碼:
% 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);
This works becaus e RandomNumbers(:)
將矩陣展開爲單個向量,並且因爲sum
爲每個真值計數1,並且每個假值爲0。
感謝您的好評!我有點困惑,你爲這兩個for循環做了什麼:對於i = 1:size(RandomNumbers,1) for j = 1:size(RandomNumbers,2)請你詳細說明一下嗎? – heinst
'size(RN,1)'返回矩陣'RN'中的行數,'size(RN,2)'返回列數。這意味着'i'遍歷所有行,'j'遍歷所有列。 – Isaac
非常感謝您的幫助...我真的很感激 – heinst