for loop in for loop not storing all variables

조회 수: 3 (최근 30일)
Dameon Solestro
Dameon Solestro 2021년 11월 22일
댓글: Walter Roberson 2021년 11월 24일
In the simplest way, I am trying to get 3 random (x,y) data sets per group with a total of 5 groups. (So 15 x coordinates and 15 y coordinates in total). Every time I use my mean(x) to find the average x. My for loop only calculates the mean for my groups of x coordinates. How do i do it for all 15 x coordinates?
for j=1:5
for i=1:3
x(i)= rand();
y(i)= rand();
hold on
end
hold on
h=mean(x)
end
h = 0.6073
h = 0.6425
h = 0.6971
h = 0.5637
h = 0.5582

채택된 답변

Walter Roberson
Walter Roberson 2021년 11월 23일
for j=1:5
for i=1:3
x(i,j)= rand();
y(i,j)= rand();
hold on
end
hold on
h(j)=mean(x(:,j))
end
h = 0.8827
h = 1×2
0.8827 0.2131
h = 1×3
0.8827 0.2131 0.4023
h = 1×4
0.8827 0.2131 0.4023 0.6954
h = 1×5
0.8827 0.2131 0.4023 0.6954 0.3230
mean(x,1)
ans = 1×5
0.8827 0.2131 0.4023 0.6954 0.3230
mean(x,2)
ans = 3×1
0.6141 0.5077 0.3881
You can see that if you stored all of the values, that mean(x,1) calculates the same thing as taking the mean of each column at the time you generate the column.

추가 답변 (1개)

Dameon Solestro
Dameon Solestro 2021년 11월 24일
Is there a way to get every x value to subtract the mean, and then place it in a matrix??
So like [(x1- mean(h) ; x2 - mean(h) ; .... ; x15-mean(h)] ??
  댓글 수: 1
Walter Roberson
Walter Roberson 2021년 11월 24일
x - mean(h)
Note that each element of your h is a mean of a column, so mean(h) would be mean of the means

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 NaNs에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by