USER420
USER420

Reputation: 337

Create an array from a loop in MATLAB?

Here is my Matlab code:

Length = length(High);
i = 1;
j = 20;

while i < Length
     HighestHIGH(i) = max(High(i:j));
     i = i+1;
     j = j+1;
end

This gives an error at HighestHIGH line. What i am trying to accomplish is: Lets assume High is an array of length 100 (Length = 100). I want to get the highest numbers of in sets of 20 in new array. Ex:

HighestHIGH[1] = max(High(1:20));
HighestHIGH[2] = max(High(2:21));
HighestHIGH[3] = max(High(3:22));
...
HighestHIGH[80] = max(High(81:100));

Upvotes: 0

Views: 306

Answers (1)

When i==Length-1, then j==Length+18 which exceeds the size of High. The upper limit of your loop is too high.

I'd write this:

N=20;
HighestHIGH=zeros(length(High)-N+1);
for i=1:length(High)-N+1
   HighestHIGH(i) = max(High(i:i+N-1));
end

Note that with what you want, the final term is HighestHIGH(81)=max(High(81:100)).

Upvotes: 1

Related Questions