0
votes

My code works when I type

if size(k)==size(k1) 
    disp('They match');
end

or

if k-k1==0
    disp('They match');
end

but if I type in two conditions at the same time like this,

if size(k)==size(k1) & k-k1==0
    disp('They match');
end

I get an error saying

Matrix dimensions must agree.

Error in practice (line 32) if size(k)==size(k1) & k-k1==0

FYI, the dimension of k and k1 are both 1x717 double. I checked it.

So I want to make an if statement that includes two conditions at the same time, but I am experiencing an error. Two && won't work cuz two && is for scalars, but my k and k1 are vectors.

Any help will be appreciated

2

2 Answers

1
votes

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.

0
votes

The problem is size(k) and size(k1) returns 1*2 vectors (number of rows and columns), so size(k)==size(k1) returns two values. On the other hand k-k1==0 returns only logical matrix with same dimension as k & k1.

For example, if k == k1, you would expect both to be equal.

size(k)==size(k1) % returns 1 1
k == k1  % returns 1

if [1 1] && 1 % gives erros

Alternatively, use isequal which will not give error even if dimensions not matching.

isequal(k,k1) % returns 1 if equal, 0 otherwise.