Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
How to optimise this?

Subject: How to optimise this?

From: Bernard.Mangay

Date: 21 Sep, 2010 15:09:52

Message: 1 of 4

I have a monotonically increasing series.

For each value in the series, I want to find the index of the next
value that is atleast a specified amount amount above it.

My code for it is below, but is slow due to too many loops. However,
I can't work out how to do it faster. Could anyone please help?


dn = cumsum((1/86400) * rand(100000,1));

seconds_10 = 10/86400;

dn2 = dn+seconds_10;

I = nan(length(dn),1);

tic;
for i=1:length(dn)

    dn2i=dn2(i);

    for j=i:length(dn)
        if dn(j)>dn2i
            I(i) = j;
            break;
        end
    end

end
toc;

Subject: How to optimise this?

From: Sean

Date: 21 Sep, 2010 15:58:04

Message: 2 of 4

"Bernard.Mangay" <fcmisc@googlemail.com> wrote in message <81648ce9-1206-427f-8947-8342b33412bc@j2g2000vbo.googlegroups.com>...
> I have a monotonically increasing series.
>
> For each value in the series, I want to find the index of the next
> value that is atleast a specified amount amount above it.
>
> My code for it is below, but is slow due to too many loops. However,
> I can't work out how to do it faster. Could anyone please help?
>
>
> dn = cumsum((1/86400) * rand(100000,1));
>
> seconds_10 = 10/86400;
>
> dn2 = dn+seconds_10;
>
> I = nan(length(dn),1);
>
> tic;
> for i=1:length(dn)
>
> dn2i=dn2(i);
>
> for j=i:length(dn)
> if dn(j)>dn2i
> I(i) = j;
> break;
> end
> end
>
> end
> toc;

This should work:
for ii=1:length(dn) %ii since i is sqrt(-1)
    test_vec = dn(ii:end)>dn2(ii);
    if any(test_vec)
        I(ii) = find(test_vec,1,'first');
    end
end

%Sean

Subject: How to optimise this?

From: Matt J

Date: 21 Sep, 2010 16:11:21

Message: 3 of 4

Another solution

[~,theResult]=histc(dn2,dn);

Subject: How to optimise this?

From: Matt Fig

Date: 21 Sep, 2010 16:15:12

Message: 4 of 4

Probably we could do a few little things like:

L = length(dn);
jj = 1;
for ii = 1:L
    dn2ii = dn2(ii);
    for jj = jj:length(dn)
        if dn(jj) > dn2ii
            I2(ii) = jj;
            break;
        end
    end
    if jj > L
        break;
    end
end

But I think the biggest time-hog is dealing with the NANs in I. Try changing to an array of zeros and see if that doesn't knock a lot of time off your run.

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us