when you compare two vectors the result would be also a vector (a logical vector), but an if
condition accept scalar logical values, so you can use all
function.
if all(size(k)-size(k1)==0) && all(k-k1==0)
disp('They match');
end
You should always use &&
in a loop, '&' is used only for logical operation AND.
I have tested this and it works:
k = rand(1,10);
k1 = k;
if all(size(k)-size(k1)==0) && all(k-k1==0)
disp('They match');
end
because when you do this:
>> k-k1==0
ans =
1×10 logical array
1 1 1 1 1 1 1 1 1 1
So the if
does not know which value to refer to. But when you do
>> all(k-k1==0)
ans =
logical
1
It gives a unique answer for all the elements of the vector.
Important Note:
Comparing numbers is not a good idea for making decisions on the loops, because of the Floating Point Error problem.
A Better War to Handle it
If you read about the floating point error problem, you will see that sometimes,
2.000 == 2.000
results to false
. In order to fix that you can do as follows:
tolerance = 0.0001;
if all(size(k)-size(k1)==0) && all(abs(k-k1)<=tolerance)
disp('They match');
end
You first define an acceptable tolerance value depending on the nature of the problem you are trying to solve and then instead of comparing the subtract to zero, you compare the absolute value of the abstract to the tolerance. Thus, the numbers such as 23.0001
and 23.000
would be considered equal.