From: Luna Moon on
tmp is an 1D array:

runningMax=zeros(size(tmp));
for m=1:length(tmp);
runningMax(m)=max(tmp(1:m));
end;


How to do it without for loop?
From: dpb on
Luna Moon wrote:
> tmp is an 1D array:
>
> runningMax=zeros(size(tmp));
> for m=1:length(tmp);
> runningMax(m)=max(tmp(1:m));
> end;
>
>
> How to do it without for loop?

OTOMH don't see a clever solution but it's likely at least as fast if
not faster to simply do the actual test instead of call max() on every
vector...

rMax(1) = tmp(1);
for idx = 2:length(tmp)
rMax(idx) = max(rMax(idx-1), tmp(idx));
end

--
From: Corey Kelly on
dpb <none(a)non.net> wrote in message <hu8vul$vet$1(a)news.eternal-september.org>...
> Luna Moon wrote:
> > tmp is an 1D array:
> >
> > runningMax=zeros(size(tmp));
> > for m=1:length(tmp);
> > runningMax(m)=max(tmp(1:m));
> > end;
> >
> >
> > How to do it without for loop?
>
> OTOMH don't see a clever solution but it's likely at least as fast if
> not faster to simply do the actual test instead of call max() on every
> vector...
>
> rMax(1) = tmp(1);
> for idx = 2:length(tmp)
> rMax(idx) = max(rMax(idx-1), tmp(idx));
> end
>
> --

An alternate way (without the loop) would be to make an array of indices, and map the max function over the two arrays. The code will be something like

RunningMax = rm = arrayfun(@(a,b) max(a(1,1:b)),tmp,1:length(tmp))

The idea is there, but something is wrong in my syntax. Perhaps an expert could fix it up for us!
From: Corey Kelly on
"Corey Kelly" <ckelly01(a)uoguelph.ca> wrote in message <hu90qd$55c$1(a)fred.mathworks.com>...
> dpb <none(a)non.net> wrote in message <hu8vul$vet$1(a)news.eternal-september.org>...
> > Luna Moon wrote:
> > > tmp is an 1D array:
> > >
> > > runningMax=zeros(size(tmp));
> > > for m=1:length(tmp);
> > > runningMax(m)=max(tmp(1:m));
> > > end;
> > >
> > >
> > > How to do it without for loop?
> >
> > OTOMH don't see a clever solution but it's likely at least as fast if
> > not faster to simply do the actual test instead of call max() on every
> > vector...
> >
> > rMax(1) = tmp(1);
> > for idx = 2:length(tmp)
> > rMax(idx) = max(rMax(idx-1), tmp(idx));
> > end
> >
> > --
>
> An alternate way (without the loop) would be to make an array of indices, and map the max function over the two arrays. The code will be something like
>
> RunningMax = rm = arrayfun(@(a,b) max(a(1,1:b)),tmp,1:length(tmp))
>
> The idea is there, but something is wrong in my syntax. Perhaps an expert could fix it up for us!

That extra assignment shouldn't be there, but that's not the main problem.
From: Jan Simon on
Dear Luna!

> dpb wrote:
> rMax(1) = tmp(1);
> for idx = 2:length(tmp)
> rMax(idx) = max(rMax(idx-1), tmp(idx));
> end

Slightly faster, at least for my test data, so please test this by your own:
b = tmp(1);
for idx = 1:length(tmp)
if tmp(idx) > b
b = tmp(idx);
end
rMax(idx) = b;
end

Jan
 |  Next  |  Last
Pages: 1 2
Prev: read serial port in real time
Next: loading a file