How to take the maximum value of an array?

Hi, I have this array a = [1:20]. How do I take the maximum value of every 5 elements of it. So I will have b = [5 10 15 20]. Anyone can help me? Thank you.

 Accepted Answer

This works:
a = [1:20];
b = max(reshape(a, 5, []));

6 Comments

And will be much faster and less typing than my solution! Kudos!
hi, thank you for kindly answer my question. it is really effective. i've tried your code like this :
but what i want is the x axis of signal b exactly like the x axis of signal a. do you have any idea how to do that? thank you...
My pleasure.
Yes, I do actually have an idea of how to do it, because I wrote the code for your earlier answer. See if this does what you want:
N = 250; % Length Of Vector
t = linspace(0, 20, N); % Time
sig = rand(1,N); % Original Signal
mtx = max(reshape(sig, 5, []));
newsig = bsxfun(@times, mtx, ones(5, size(mtx,2)));
newsig = reshape(newsig, [], length(sig)); % New Signal
figure(1)
subplot(2,1,1)
plot(t, sig)
grid
subplot(2,1,2)
plot(t, newsig)
grid
It works with my test vector, see if it works with your signal.
@Greig — It’s a code shortcut of the sort that frequently appears here on ‘Answers’. I’m frequently amazed at the Answers the truly gifted people here submit.
and I'm truly amazed with your answer.. aaa thank you so much Star Strider!

Sign in to comment.

More Answers (1)

Try something like this...
a=1:20;
steps = 5;
b = NaN(mod(length(a)/steps,steps), 1); % preallocate b for speed, if you want to run larger loops
count = 1; % an index count for b in the loop
for ii = 1:steps:length(a)-(steps-1)
inds = ii:ii+(steps-1); % The indices we are interested in
b(count) = max(a(inds)); % Get the max
count = count+1; % add 1 to the counter
end

1 Comment

hi, thank you for kindly answer my question. but what i want is the x axis of signal b exactly like the x axis of signal a. do you have any idea how to do that? thank you...

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!