3

I'm using matlab and want to check whether a column vector is equal to another withing 3dp, to do this i'm trying to create an array full of 0.001 and checking whether it is greater than or equal. is there a simpler way than a for loop to create this array or no?

4 Answers 4

10

is there a simpler way than a for loop to create this array or no?

Yes, use

ones(size, 1) * myValue

For instance

>> ones(5,1)*123

ans =

   123
   123
   123
   123
   123
Sign up to request clarification or add additional context in comments.

Comments

4

So, let me know if this is correct.

You have 2 vectors, a and b, each with N elements. You want to check if, for each i<=N, abs(a(i)-b(i)) <= 0.001.

If this is correct, you want:

vector_match = all(abs(a-b) <= 0.001);

vector_match is a boolean.

Comments

1

Example:

a = rand(1000,1);
b = rand(1000,1);

idx = ( abs(a-b) < 0.001 );
[a(idx) b(idx)]

» ans =
       0.2377      0.23804
       0.0563     0.056611
      0.01122     0.011637
        0.676       0.6765
      0.61372      0.61274
      0.87062      0.87125

Comments

0

You may consider the 'find' command, like:

a = [ 0.005, -0.003 ];
x = find(a > 0.001);

FWIW, I've found comparing numbers in MATLAB to be an absolute nightmare, but I am also only new to it. The point is, you may have floating-point comparision issues when do you the compares, so keep this in mind when attempting anything (and someone please correct me if I'm wrong on this or there is a beautiful workaround.)

2 Comments

To deal with comparison issues, you can use eps. In general, floating-point comparison affects all languages, not just MATLAB. You can read some materials on numerical methods because the numerical errors may accumulate after a large number of operations. For example, in some cases it is sqrt(eps).
@wrong: Sure, I know about eps, and I know about floating point comparisions, but eps doesn't always help. Thanks though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.