1

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?

thepro22
  • 169
  • 1
  • 4
  • 10
  • I am trying to create a 3rd 100 X 1 matrix (same # of rows as MATRIX 1) which contains the mean values. – thepro22 Aug 24 '11 at 17:10

4 Answers4

7

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));
gnovice
  • 125,304
  • 15
  • 256
  • 359
4

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))
bnaul
  • 17,288
  • 4
  • 32
  • 30
  • This is often a better approach since Matlab doesn't generally handle `for` loops efficiently – PengOne Aug 24 '11 at 19:27
  • Note, however, that `cellfun` / `arrayfun` are often even more inefficient than `for` loops: http://stackoverflow.com/questions/12522888/arrayfun-can-be-significantly-slower-than-an-explicit-loop-in-matlab-why http://stackoverflow.com/questions/16143314/matlab-arrayfun-cellfun-spfun-and-structfun-vs-simple-for-loop – Luis Mendo Oct 01 '13 at 10:30
3

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)
carlpett
  • 12,203
  • 5
  • 48
  • 82
3

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

Ben Duong
  • 31
  • 1