# Need help finding out if I wrote this code correctly

1 view (last 30 days)

Show older comments

N = 365;

n = (1:80);

for M = 1:1000

j = (1:n);

pn = 1-(1-((n-1)/N));

end

%%

fig = figure(1); clf

plot(pn)

xlabel('Value')

ylabel('Probability')

ylim(x,0.3)

### Answers (2)

Star Strider
on 5 Sep 2022

Edited: Star Strider
on 5 Sep 2022

If you want to save the values of ‘pn’ in the loop, subscript it —

pn(M) = 1-(1-((n-1)/N));

That will create a row vector that you can then plot.

What is the ‘j’ calculation supposed to do? The code calculates it in each iteration and never uses it (at least not that I can see).

##### 2 Comments

Walter Roberson
on 5 Sep 2022

n is a vector, so you would have to assign to either pn(M,:) or pn(:,M)

Star Strider
on 5 Sep 2022

Edited: Star Strider
on 5 Sep 2022

I just now noticed that.

EDIT — (5 Sep 2022 at 13:16)

I believe this is the ‘Birthday Problem’ the solution of which is simply:

N = 365;

V = 1:N;

pn = cumprod((N:-1:1) / N);

Result = [V; pn]

Eq = find(pn >= 0.5, 1, 'last')

I don’t understand the reason that it needs to be simulated 1000 times unless some different sort of calculation is involved.

.

Walter Roberson
on 5 Sep 2022

n = (1:80);

n is a vector.

for M = 1:1000

j = (1:n);

n is a vector, so j is 1:VECTOR instead of being 1:SCALAR or 1:SCALAR:SCALAR . You have a logic error there. What MATLAB does in this particular case is to define the output as if you had written 1:VECTOR(1) . Since n = 1:80 then n(1) is 1, so you are effectively defining j = 1:1 which is the same as j = 1

pn = 1-(1-((n-1)/N));

but you never use j in the calculation or afterwards, so there is no point calculating it.

You overwrite all of pn in the calculation. The end result is the same if you had only done the last iteration, when M = 1000.

You did not include any comments, so we cannot tell what you are trying to calculate, so we cannot suggest what correct code might be. (But I get the impression that possibly you are testing out the "Birthday Paradox" ?)

##### 4 Comments

Walter Roberson
on 5 Sep 2022

It is not very meaningful to talk about probability without random numbers, or at least without cdf or pdf formulas.

1-(1-((n-1)/N))

1-(n-1)/N is 1/N

1 - 1/N is (n-1)/N

Therefore your current formula is calculating the same thing as (n-1)/N

If you were doing something like birthday paradox, you would be doing a calculation similar to

1-(1-((n-1)/N).^POWER)

for appropriate POWER -- if, that is, you were calculating based on the closed-form solution, rather than doing it as an "experiment".

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!