Reputation: 31
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?
Upvotes: 3
Views: 15668
Reputation: 6921
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
Upvotes: 10
Reputation: 67849
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.
Upvotes: 4
Reputation: 124563
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
Upvotes: 1
Reputation: 55172
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.)
Upvotes: 0