function based of the first n elements of a matrix

I have a matrix, A, with 40000 binomial random elements. I am trying to complete the following code and would appreciate help:
I need to create 40000 arrays X_n, where X_n represents the array containing the first n elements of the matrix A for each n:[1,40000]
then for each X_n I need to calculate the value of the function, O_n = (the number of elements of X_n that are less than 25)/n
(This is all based around trying to approximate the proportion of overbookings of a flight. The matrix A is 40000 simulations of my situation.)

2 Comments

It is unclear to me. So X_1 will have one element, X_2 two, and so on?
Yes. X_1 represents the array that contains the first element of A. X_2 represents the array with the first two elements of A and so on.

Sign in to comment.

Answers (1)

Cedric
Cedric on 29 Jan 2015
Edited: Cedric on 29 Jan 2015
Based on what I understand, i.e. that you don't really need to build the X_n arrays, but just the O_n results, I propose that you compute directly O_n for all n. Here is a demo with a 10x1 numeric array A (for sake of simplicity), that we populate with random integers between 1 and e.g. 60:
>> A = randi( 60, 10, 1 )
A =
8
30
58
21
36
14
46
16
31
42
We start by creating a vector of logicals testing for the conditon "is less than 25" ( <25) :
>> results = A < 25
results =
1
0
0
1
0
1
0
1
0
0
We perform a cumulative sum of these 1's taken as integers, and we get, for each index, the count of elements lower than 25 from the first element to this index:
>> results = cumsum( results )
results =
1
1
1
2
2
3
3
4
4
4
Finally, we divide each count by its index ( n in your statement):
>> results = results ./ (1:numel(A)).'
results =
1.0000
0.5000
0.3333
0.5000
0.4000
0.5000
0.4286
0.5000
0.4444
0.4000
At this stage, results is a vector of what the function O_n of your statement would output for each n.
Putting everything together, you get the following one liner:
>> results = cumsum( A < 25 ) ./ (1:numel( A )).'
results =
1.0000
0.5000
0.3333
0.5000
0.4000
0.5000
0.4286
0.5000
0.4444
0.4000

Categories

Asked:

Dst
on 29 Jan 2015

Edited:

on 29 Jan 2015

Community Treasure Hunt

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

Start Hunting!