MATLAB: comparing all elements of two arrays
Solution 1
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).
Solution 2
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
n0ob
Updated on June 04, 2022Comments
-
n0ob almost 2 years
I have two matrices in MATLAB lets say
arr1
andarr2
of size 1000*1000 each. I want to compare their elements and save the comparison in a result matrixresarr
which is also 1000*1000 such that for each element:- if the element in
arr1
is bigger than the one inarr2
, place the value 1 in the result - if the element in
arr2
is bigger, store the value 2
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
andarr2
, could that be done without slow loops?For example store (255,0,0) if
arr1
is larger and (0,255,0) ifarr2
is larger - if the element in
-
n0ob about 14 yearscan you tell me what I would do if I wanted to assign different RGB value to a 1000*1000*3 result array, depending on the comparison results of arr1 and arr2??
-
Amro about 14 yearsAs a remark, even though this code is correct, performance-wise note that by storing 1/2 instead of true/false you are creating a matrix x8 times the size of the logical type..