user36729
user36729

Reputation: 575

A function to calculate cumulative maximum for a double matrix in MATLAB

Is there any function that can calculate cumulative maximum for a double matrix? I have a 1*3000 matrix and I need to calculate the cumulative maximum. For example if the matrix is:

A = [8     3     6     7     9    10     6     2     2     3]

The cumulative maximum array will be:

B = [8     8     8     8     9    10    10    10    10    10]

I have tried cummax function but I faced this error:

Undefined function 'cummax' for input arguments of type 'double'

Upvotes: 1

Views: 491

Answers (2)

Dan
Dan

Reputation: 45752

Here is an alternative that uses bsxfun:

max(bsxfun(@(~,y)([A(1:y),-inf(1,numel(A)-y)]'), A', 1:numel(A)))

Upvotes: 1

user1543042
user1543042

Reputation: 3440

If cummax isn't working then I came up with this little function

function m = cummax2(x)
    [X, ~] = meshgrid(x, ones(size(x)));
    %replace elements above diagonal with -inf
    X(logical(triu(ones(size(X)),1))) = -inf;
    %get cumulative maximum
    m = reshape(max(X'), size(x));
end

Upvotes: 1

Related Questions