Find series of maxima of array (and matrix) within blocks of size n

2 Ansichten (letzte 30 Tage)
Erez
Erez am 30 Aug. 2019
Kommentiert: Erez am 30 Aug. 2019
I have a simple problem, and it's, perhaps, less simple extension:
  1. I have an array A=[1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5] (all positive). How do I produce a vector B, which contains the maxima of, say, blocks of n=5 within A?
Namely, I want to produce B=[5 5 5 5].
2. I have a matrix: A=[1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5; 1 2 5 1 0 0 7 0 1 2 4 0 7 3 2 0 1 0 0 5; 1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5;] . Now, I want to get the matrix: C=[5 5 5 5; 5 7 7 5; 5 5 5 5] .
Can these two tasks be achomplished with a single procedure, without using loops?
Thanks!

Akzeptierte Antwort

Ted Shultz
Ted Shultz am 30 Aug. 2019
Bearbeitet: Ted Shultz am 30 Aug. 2019
You could use rehsape and max:
[reshape(max(reshape(A',5,[])), [], size(A,1))]'
Test:
A=[1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5]
[reshape(max(reshape(A',5,[])), [], size(A,1))]'
A=[1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5; 1 2 5 1 0 0 7 0 1 2 4 0 7 3 2 0 1 0 0 5; 1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5;]
[reshape(max(reshape(A',5,[])), [], size(A,1))]'
ans =
5 5 5 5
ans =
5 5 5 5
5 7 7 5
5 5 5 5

Weitere Antworten (1)

Bruno Luong
Bruno Luong am 30 Aug. 2019
Bearbeitet: Bruno Luong am 30 Aug. 2019
maxfun = @(A) squeeze(max(reshape(A,size(A,1),5,[]),[],2));
A = [1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5]
B = maxfun(A)
A = [1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5; 1 2 5 1 0 0 7 0 1 2 4 0 7 3 2 0 1 0 0 5; 1 2 5 1 0 0 5 0 1 2 4 0 5 3 2 0 1 0 0 5]
C = maxfun(A)
  1 Kommentar
Erez
Erez am 30 Aug. 2019
Awsome solution! I can't formally accept two solutions on this website, so I'll "accept" the first (arbitrarily). But this solution of yours works just as great. Thanks!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by