0

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).

Community
  • 1
  • 1
Hamed
  • 1,175
  • 3
  • 20
  • 46
  • 2
    Isn't `max(A,B)` what you want? From the [documentation](http://es.mathworks.com/help/matlab/ref/max.html): _MAX(X,Y) returns an array the same size as X and Y with the largest elements taken from X or Y. Either one can be a scalar._ – Luis Mendo Oct 14 '15 at 14:01
  • Your code would take the minimum anyway, because when A > B you assign something smaller. – Pieter21 Oct 14 '15 at 14:02
  • @ Pieter21 thank you I corrected it – Hamed Oct 14 '15 at 14:07
  • 1
    @Luis Mendo yes you are right I was overthinking – Hamed Oct 14 '15 at 14:10

1 Answers1

1
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

BillBokeey
  • 3,168
  • 14
  • 28
  • you can do the comparison in the last one once and use it on the arrays to shave more time. – percusse Oct 14 '15 at 14:06
  • although I was overthinking, your answer to this question is right and very helpful on understanding the `bsxfun` functionality, thanks – Hamed Oct 14 '15 at 14:20