필터 지우기
필터 지우기

calculate mean using while and iteration?

조회 수: 1 (최근 30일)
Madan Kumar
Madan Kumar 2019년 4월 30일
댓글: Madan Kumar 2019년 5월 3일
Hi,
I have data of ~3500x2. I want to calulate mean of second column for a particular condition in first column using 'while'.
let data (a, b) be like
0.5 1.8
0.6 1.5
0.9 1.8
1.0 1.5
1.1 1.4
1.2 1.4
1.5 1.6
1.8 1.2
2.1 1.2
2.3 1.3
2.4 1.5
2.6 1.8
2.9 2.0
3.0 3.0
3.12 3.2
3.15 1.9
3.16 1.7
3.18 2.2
I need to calculate mean of b, if a> 0.5 and a<1.5. Then increase 'a' by 1 and calculate mean of b (i.e for a > 1.5 and a<2.5) and so on. It may be a silly question but I am stuck with it. My code is
del=0.5;
k=1;
a(k)=1;
while(a(k) >(a(k)-del) && a(k)< (a(k)+del))
xn(k)=mean(b(k));
k= k+1;
a(k)=a(k)+1;
end
but it shows error Index exceeds array bounds.
Error in untitled (line 12)
a(k)=a(k)+1;
Thank you for your help.
  댓글 수: 2
David Wilson
David Wilson 2019년 4월 30일
편집: David Wilson 2019년 4월 30일
My code below is a bit ugly, but I think it does what you want:
cutoff = [0.5 1.5]; % band of interest
maxA = ceil(max(a))+0.5;
bmean = [];
for i=1:maxA
idx = find(a>cutoff(1) & a<cutoff(2));
bmean(i) = mean(b(idx));
cutoff = cutoff+1;
end
The means of column "b" are in variable bmean.
I note that you specified strict < as opposed to <= which may, or may not be what you really want.
Note that column a need not be sorted in increasing order.
Madan Kumar
Madan Kumar 2019년 4월 30일
Thank you...

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

채택된 답변

Rik
Rik 2019년 4월 30일
So you want to calculate these values?
xn(1)=mean(b(a>0.5 & a<1.5));
xn(2)=mean(b(a>1.5 & a<2.5));
xn(3)=mean(b(a>2.5 & a<3.5));
etc?
You don't need a while loop for that:
a=[0.5 0.6 0.9 1.0 1.1 1.2 1.5 1.8 2.1 2.3 2.4 2.6 2.9 3.0 3.12 3.15 3.16 3.18];
b=[1.8 1.5 1.8 1.5 1.4 1.4 1.6 1.2 1.2 1.3 1.5 1.8 2.0 3.0 3.2 1.9 1.7 2.2];
del=0.5;
xn=zeros(1,ceil(max(a-del)));
for k=1:size(xn,2)
xn(k)=mean(b(a>(k-del) & a<(k+del)));
end
  댓글 수: 4
Stephen23
Stephen23 2019년 4월 30일
편집: Stephen23 2019년 4월 30일
"Suppose, I need xn(0.5)=... "
You can't. Indices must be whole integers greater than zero.
Either change del to 0.25 and leave it at that, or write a function which lets you have any input values that you desire. But you certainly cannot have indexing with non-integer values.
Madan Kumar
Madan Kumar 2019년 5월 3일
Ok...thank you...

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

추가 답변 (1개)

KSSV
KSSV 2019년 4월 30일
Why loop? YOu can use inbuilt in mean. Let a,b be your columns.
idx = a>0.5 & a<1.5 ;
mean(b(idx))

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by