Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

matlab - How do I compare all elements of two arrays?

I have two big arrays with about 1000 rows and 1000 columns. I need to compare each element of these arrays and store 1 in another array if the corresponding elements are equal.

I can do this with for loops but that takes a long time. How can I do this faster?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The answers given are all correct. I just wanted to elaborate on gnovice's remark about floating-point testing.

When comparing floating-point numbers for equality, it is necessary to use a tolerance value. Two types of tolerance comparisons are commonly used: absolute tolerance and relative tolerance. (source)

An absolute tolerance comparison of a and b looks like:

|a-b| < tol

A relative tolerance comparison looks like:

|a-b| < tol*max(|a|,|b|) + tol_floor

You can implement the above two as anonymous functions:

%# absolute tolerance equality
isequalAbs = @(x,y,tol) ( abs(x-y) <= tol );

%# relative tolerance equality
isequalRel = @(x,y,tol) ( abs(x-y) <= ( tol*max(abs(x),abs(y)) + eps) );

Then you can use them as:

%# let x and y be scalars/vectors/matrices of same size
x == y
isequalAbs(x, y, 1e-6)
isequalRel(x, y, 1e-6)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...