MATLAB: How to replace consecutive 4 elements of an array with the largest element among every 4 consecutive element

matrix manipulation

a=[12 58 16 56 23 7 8 45 53 56 12 32 65 12 23 54];
b=zeros(16,1)
for i=1:4:16
for i=1:1:4
if (a(i)>=a(i+1) && a(i)>=a(i+2) && a(i)>=a(i+3));
b(i)=a(i);
b(i+1)=a(i);
b(i+2)=a(i);
b(i+3)=a(i);
elseif (a(i+1)>=a(i) && a(i+1)>=a(i+2) && a(i+1)>=a(i+3));
b(i)=a(i+1);
b(i+1)=a(i+1);
b(i+2)=a(i+1);
b(i+3)=a(i+1);
elseif (a(i+2)>=a(i) && a(i+2)>=a(i+1) && a(i+2)>=a(i+3));
b(i)=a(i+2);
b(i+1)=a(i+2);
b(i+2)=a(i+2);
b(i+3)=a(i+2);
else
b(i)=a(i+3);
b(i+1)=a(i+3);
b(i+2)=a(i+3);
b(i+3)=a(i+3);
end
end
end
b should be [58 58 58 58 45 45 45 45 56 56 56 56 65 65 65 65]

Best Answer

The other two answers are good for what you asked. One other way I'll just mention is that you can use blockproc() to move along in "jumps" of 4 elements and take the max. Although slightly more compact, it's more cryptic (as compact code often is) and not as easy to understand what it's doing so I won't give it.
Another, related, option (that you didn't ask for but I'll just lay out there for completeness) is to use imdilate() to do "morphological dilation". The constraint though is that it moves along one element at a time as it slides the 4-element window along.
b = imdilate(a, true(1,4));
Again, the window there slides by 1, not in jumps of 4. It's basically a sliding local max filter.