thepro22
thepro22

Reputation: 169

Creating a loop in MATLAB to find means

So I have 2 matrices in MATLAB. If one of them is a 100 X 2 matrix, like this:

[a b]
[13 19]
[21 39]
[35 45] 

ect. ect.

and the other matrix is a N X 1 matrix with values like this:

[1]
[3]
[5]
[7]

ect. ect.

What I'm trying to do is find the Mean value of all the elements from 'a' to 'b' of the 2nd matrix.

What I've got so far is this: (If my first matrix is called: MATRIX1

second matrix is called: MATRIX2)

a= MATRIX1(1:1)
b= MATRIX1(1:2)
values = MATRIX2(a:b)
mean(values)

this gives me exactly what I want, the mean of the values from a to b. But how do I create a loop so that I can do this automatically for all the rows in MATRIX 1?

Thanks!

Update: I figured out how to get a loop, but now I'm not sure how to take all my values and make it into a 100 X 1 matrix. This is the code I used:

c= size(MATRIX1,1);

for k= 1:c;
    a= MATRIX1(k,1);
    b= MATRIX1(k,2);
    values= MATRIX2(a:b);
    d= mean(values)
end

with this, I get 100 values of d. How do I put these values into a 100 X 1 matrix?

Upvotes: 1

Views: 6183

Answers (4)

bnaul
bnaul

Reputation: 17636

Looks like I'm already beaten, but just for the sake of variety, another option using cellfun is:

cellfun(@(pair) mean(x(pair(1):pair(2))), num2cell(inds, 2))

Upvotes: 4

gnovice
gnovice

Reputation: 125874

Here's how to do this with a for loop:

nRows = size(MATRIX1,1);
meanValues = zeros(nRows,1);
for row = 1:nRows
  meanValues(row) = mean(MATRIX2(MATRIX1(row,1):MATRIX1(row,2)));
end

Another way to do this is to use the function ARRAYFUN like so:

meanValues = arrayfun(@(a,b) mean(MATRIX2(a:b)),MATRIX1(:,1),MATRIX1(:,2));

Upvotes: 7

Ben Duong
Ben Duong

Reputation: 31

just for clarification you want something that takes the "a"th element in matrix 2 to the "b"th element and averages all of those values?

This should work:

[r c] = size(MATRIX1);
myMeans = zeros(r,1);

for i = 1:r
   myMeans(i) = mean(MATRIX2(MATRIX1(i,1):MATRIX1(i,2)))
end

this will store all of the means for the rows in myMeans

Upvotes: 3

carlpett
carlpett

Reputation: 12613

You are almost there!

elems = 100
values = zeros(1, elems)
for row = 1:elems
  a= MATRIX1(1:1)
  b= MATRIX1(1:2)
  values(row) = MATRIX2(a:b)
end
mean(values)

Upvotes: 3

Related Questions