简体   繁体   中英

Matlab equivalent of Python's 'reduce' function

I have a bunch of matrices of the same size m*n: a, b, c, d , and I'd like to find the maximum of them elementwise, like:

mx = max(a, max(b, max(c, d)));

apparently the code above is not concise enough, I've googled and didn't find much help about max on N matrices, or any matlab function like python's reduce . I haven't learned much about matlab, so is there one?

Make a n*m*4 matrix of your input, then you can use max :

M=cat(3,a,b,c,d)
max(M,[],3)

The cat with parameter 3 concatenates your matrices along the third dimension, and max finds the maximum along this dimension. To be compatible with arbitrary matrix dimensions:

d=ndims(a)
M=cat(d+1,a,b,c,d)
max(M,[],d+1)

Reduce itself does not exist, and typically you don't need it because multi dimensional inputs or varargin do the trick, but if you need it, it's simple to implement:

function r=reduce(f,varargin)
%example reduce(@max,2,3,4,5)
while numel(varargin)>1
    varargin{end-1}=f(varargin{end-1},varargin{end});
    varargin(end)=[];
end
r=varargin{1};
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM