Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement comparions: Matrix and number [closed]

Tags:

matlab

I have a matrix A = [0 4 5 3] and the the number B=4. No I want to do the following.

if A<B
    disp('Something')
end

But this doesn't work, Matlab wont compare a matrix to a number. How can I solve this.

like image 257
user1200276 Avatar asked Dec 01 '25 06:12

user1200276


1 Answers

Matlab will compare a matrix (or, more properly, an array) to a number, the result of that operation will just be another array (of type logical). Boolean tests in if- and for-statements require a single logical to operate on. You need to convert your logical array to a single value by using any() (will return true if any of the elements is true) or all() (will return true if all of the elements are true).

For example:

if any(A<B)
    disp('Something');
end

For more insight into what's going on:

>> A = [0 4 5 3]; B = 4;
>> A < B
ans =
     1     0     0     1

>> any(A<B)
ans =
     1

>> all(A<B)
ans =
     0
like image 184
EelkeSpaak Avatar answered Dec 02 '25 22:12

EelkeSpaak