close all;
hold on
%Edited
M = zeros(100,500);
%
for count = 0:99
x = [];
p = 0;
for i = 1:499
n = rand(1);
if n > 0.5
p = p+1;
end
if n < 0.5
p = p-1;
end
x(i) = p;
end
%Edited
for j = 1:500
M(n,j) = x(j);
end
%
X = abs(x);
Y = 1:length(X);
ps = csapi(X,Y);
fnplt(ps)
end
hold off
grid on
title('Random Walk Distances')
xlabel('Distance from the Origin')
ylabel('Each Iteration of the Experiment')
我的意圖是找出代碼繪製的所有曲線的平均曲線。爲此,我正在考慮爲數組的每個索引尋找平均值,然後繪製該曲線,但是,我只保留最後一次迭代的值,我如何將所有值存儲在大矩陣中。在每個循環後存儲數組
編輯:我已經包圍了我正在考慮的變化(%),但它不起作用。 國家:
錯誤Random_walk_1D(第30行)
M(N,j)的= X(N);
下標索引必須是實數正整數或邏輯。
[預分配內存](https://de.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html)獲取正確大小的矩陣,並將結果存儲到循環內該矩陣的適當索引處。 – mikkola
你有一個如何做到這一點的例子嗎?如果'n'是例如 – James
'0.3',那麼'M(0.3,j)'是錯的,不是嗎?因爲好的,下標指數必須是真實的正整數或邏輯。 –