n0ob
n0ob

Reputation: 1285

MATLAB: comparing all elements of two arrays

I have two matrices in MATLAB lets say arr1 and arr2 of size 1000*1000 each. I want to compare their elements and save the comparison in a result matrix resarr which is also 1000*1000 such that for each element:

but I don't want to do this with for loops because that is slower. How can I do this?


EDIT: Also if I wanted to store different RGB values in a 1000*1000*3 result matrix, depending on the comparison of arr1 and arr2, could that be done without slow loops?

For example store (255,0,0) if arr1 is larger and (0,255,0) if arr2 is larger

Upvotes: 2

Views: 10158

Answers (2)

Ofri Raviv
Ofri Raviv

Reputation: 24823

resarr = 2 - (arr1 > arr2)

arr1>arr2 compares arr1 and arr2, element by element, returning 1000x1000 matrix containing 1 where arr1 is larger, and 0 otherwise. the 2 - part makes it into a matrix where there are 1's if arr1 was larger than arr2, and 2's otherwise.

note: if arr1 and arr2 are euqal at some point, you'll also get 2 (because arr1>arr2 return 0, then 2-0=2).

Upvotes: 5

gnovice
gnovice

Reputation: 125854

With respect to your edit, once you have your resarr matrix computed as Ofri suggested, you can modify an RGB matrix img in the following way:

N = numel(resarr);  %# The number of image pixels

index = find(resarr == 1);  %# The indices where arr1 is bigger
img(index) = 255;           %# Change the red values
img(index+N) = 0;           %# Change the green values
img(index+2*N) = 0;         %# Change the blue values

index = find(resarr == 2);  %# The indices where arr2 is bigger
img(index) = 0;             %# Change the red values
img(index+N) = 255;         %# Change the green values
img(index+2*N) = 0;         %# Change the blue values

Upvotes: 2

Related Questions