Adding a new value to an array within a loop

13 ビュー (過去 30 日間)
VS
VS 2020 年 5 月 8 日
コメント済み: VS 2020 年 5 月 8 日
Hi, this is my code. For each m, I am generating a random data set with 23 elements, then sum up the elements and add the sum to the array t1_0. However the resulting array has just the last added sum, all the other values are zeros. I cannot figure out what I am doing wrong. Many thanks for help.
clc; clear all;
rng('default') % initialize random number generator
A = 1.1; mn = 0; sd = 1; N = 23;
m = 3;
t1_0 = zeros(m,1)
for i=1:m % generate m outcomes of the data set
% generate a single data set under hypothesis H0
x0 = randn(N,1)*sd + mn;
sum(x0)
% statistic T1 under hypothesis H0
t1_0(m) = sum(x0);
end
t1_0
%T1_H0 = histogram(t1_0,50,'Normalization','pdf');
This is the output I get when I print out the values of sums for each m (m=3) and the final array:
ans =
13.4730
ans =
-1.9366
ans =
0.5020
t1_0 =
0
0
0.5020

採用された回答

Rik
Rik 2020 年 5 月 8 日
You aren't correctly indexing:
%replace this
t1_0(m) = sum(x0);
%with this
t1_0(i) = sum(x0);
  1 件のコメント
VS
VS 2020 年 5 月 8 日
Thanks!

サインインしてコメントする。

その他の回答 (1 件)

Mehmed Saad
Mehmed Saad 2020 年 5 月 8 日
because you are passing m to t1_0 and value of m is constant through out the for loop. The index of your for loop is i in this case so replace m with i in t1_0
  1 件のコメント
VS
VS 2020 年 5 月 8 日
Thanks!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by