简体   繁体   中英

Efficient element wise function on two matrices in MATLAB

I have two matrices A and B and I want to perform an element wise maximum on them. I just wrote the following code which is very inefficient and takes a long time to run.

A = C;
for x = 1 : height
    for y = 1 : width
        if(A(x, y) < B(x, y))
            A(x, y) = B(x, y);
        end
    end
end 

I searched SO and figured out that similar questions have been answered using bsxfun function ( 1 , 2 , 3 ). But I could not get the point.

can bsxfun be applied here too?

What I want would be something like A = max(B, C) .

bsxfun(@(x,y) x<y,A,B)

Will return the indexes where A>B.

So :

A(bsxfun(@(x,y) x<y,A,B))=B(bsxfun(@(x,y) x<y,A,B));

Should do the trick.

But no need to use bsxfun, you can just go :

A(A<B)=B(A<B);

Or just use max (shame on me) as stated in the comments

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