trouble using "mean" function in MATLAB?

2 views (last 30 days)
Anand Anand
Anand Anand on 23 Oct 2012
consider A=[1 2 3] if i use mean(A(1):A(3)) it gives 2 which is the mean of first element and third element of A.
if A=[3 2 1],and if i use mean(A(1):A(3)) then it says NaN. Why should this occur?shouldnt the command just give the mean of the first and third digit in the array?Any help will be appreciated...

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 23 Oct 2012
Maybe you want
mean(A(1:3))

Matt Fig
Matt Fig on 23 Oct 2012
You are creating a vector with the elements of A, rather than indexing into A with a vector. Look at what happens:
A = [1 2 3];
B = A(1):A(3) % Same as:
B2 = 1:3 % Read: make a vector from 1 to 3 in steps of 1
isequal(B,B2)
A = [3 2 1];
B = A(1):A(3) % Same as:
B2 = 3:1 % Read: make a vector from 3 to 1 in steps of 1
isequal(B,B2)
Probably what you want to do is index into A with a vector:
A(1:3) % Read: take elements 1 through 3 of A.

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!