how to create logical matrix directly in matlab

I have so far been using

 a = logical(zeros(10,10))

to create logical matrix.

Is there a way to create it directly?

Answers


Use false directly:

a = false(10,10);

In Matlab, there are a few 'constants' that are actually matrix-generating commands. They are:

true(10);   true(n,m,k,..);   % for an all-true  10-by-10 or n-by-m-by-k-by-...matrix
false(10);  false(n,m,k,..);  % for an all-false 10-by-10 or n-by-m-by-k-by-...matrix
inf(10);    inf(n,m,k,..);    % for an all-inf   10-by-10 or n-by-m-by-k-by-...matrix
nan(10);    nan(n,m,k,..);    % for an all-nan   10-by-10 or n-by-m-by-k-by-...matrix

The 'constant' forms are basically just aliases:

a = inf;   % alias for a = inf(1);
b = true;  % alias for b = true(1);

etc. Also, here are some more things that cannot be repeated enough:

rand(10);  rand(n,m,k,..);    % for an all-random 10-by-10 or n-by-m-by-k-by-...matrix
zeros(10); zeros(n,m,k,..);   % for an all-zero   10-by-10 or n-by-m-by-k-by-...matrix
zeros(n,m,k,...,'uint8');     % for an all-zero   n-by-m-by-k-by-...matrix of type uint8
ones(10); zeros(n,m,k,..);    % for an all-one    10-by-10 or n-by-m-by-k-by-...matrix
ones(n,m,k,...,'uint8');      % for an all-one    n-by-m-by-k-by-...matrix of type uint8
eye(10); eye(n,m,'uint8');    % for an identity matrix of type uint8 of 10-by-10 or n-by-m

Matlab's logical data type does not appear to have a constructor other than the logical function itself. That being said, you can effectively typecast a double array as a logical array very easily, where all nonzero values become logic 1 and all zeros logic 0:

A = [1 0 2; -1 0 0; 0 1.53 -100.00]

B = logical(A)

B = 
   1     0     1
   1     0     0
   0     1     1

You can obviously condense this assignment to one line if you'd like, so it becomes nearly as simple as assigning any other data type.


Need Your Help

Unit testing Spring @Around AOP methods

spring aop aspectj

I can unit test most of my Spring classes without needing to do Spring "stuff".