user2611994
user2611994

Reputation: 3

Matlab plot won't return correct results

I have written a function that is the beginning of a Poisson Process

function n_t = PoisProc2(t,tao,SIZE)

n_t=0;

for n=1:SIZE

    if t>tao(1,n)
        n_t=n_t+1;
    end

end


end

tao is simply an array of random doubles of length SIZE. For simplicity we'll say [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,20]

So this functions purpose is to count how many elements of tao that t is greater than for any given t.

This code works fine when I simply write

PoisProc2(3,tao,20);

the answer I get is 19 as expected, but if I write

x=1:.01:20;
y=PoisProc2(x,tao,20);
plot(x,y,'-')

y shows up as 0 in the workspace (I would expect an array of length 1901) and my plot also reads 0. I'm pretty new to Matlab, but this seems like a pretty simply thing I'm trying to do and I must be missing something obvious. Please help!

Upvotes: 0

Views: 83

Answers (2)

xmo
xmo

Reputation: 785

Because x is a vector in your last example, the "if t>tao(1,n)" statement in your function behave totally different from what you think.

This function below should give you the right result.

function ret = PoisProc2(thresholds, vec)
ret = zeros(size(thresholds));
for k = 1:numel(thresholds)
    ret(k) = numel(nonzeros(vec > thresholds(k)));
end

Side comments:

  • Your original function is quite C/Java style. You can see in my function, it's replaced by a one-liner "numel(nonzeros(vec > thresholds(k)))", which is more MATLAB style.
  • I think this can be done with hist() function. But this probably is easier to understand.

Upvotes: 0

David
David

Reputation: 1136

Your code does not work as you are giving a vector. So your if condition is not working as you expect.

First initialize n_t with a vector :

n_t=zeros(1,length(t))

instead of

if t>tao(1,n)
    n_t=n_t+1;
end

Vectorize your expression :

n_t = n_t + (t>tao(1,n))

Cheers

Upvotes: 1

Related Questions