Why comparing matrices is not evaluated as boolean in Octave?

ⅰ亾dé卋堺 提交于 2019-12-04 06:02:23

问题


Im new to Octave and playing around with the console.

why when comparing matrices, the expression is not evaluates as boolean :

example:

>> A=[1,2;3,4];     % creating 2x2 matrix
>> 5 == 5           % sample comparison returns true (1)
ans = 1

>> A(1,1) == A(1,1) % single element comparison returns true (1)
ans = 1

>> A == A           % returns 2x2 matrix ???
ans =

  1  1
  1  1

>> size(A == A)     % prove that the above returns 2x2 matrix
ans =

   2   2

回答1:


== is for element-wise comparison of two matrices. To check whether two matrices are same or not, use isequal.




回答2:


Sardar's answer is correct, but when it comes to computational time, I think that my alternative answer is better: You can as well check that all elements of the boolean matrix A == A are 1, i.e., that the sum of 1s in the matrix A==A equals the number of elements of A, i.e:

sum((A == A)(:)) == numel(A)

ans = 1

Where the operator (:) simply vectorizes the matrix A==A so that it can be added with sum(). Compare the two answers when you matrix is quite big, for instance by defining A = rand(1e4), the computation time is considerably different...



来源:https://stackoverflow.com/questions/53252570/why-comparing-matrices-is-not-evaluated-as-boolean-in-octave

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!