How to check if cell's elements contain matrix

I have a cell described as the following:

  mixed_values = {'jim', 89, [5 2 1; 1 2 3]};
  mixed_values{1}    
  mixed_values{2}
  mixed_values{3} 

I loop it:

for k=1:length(mixed_values)
  curstate=mixed_values{k};

% Check for the [5 2 1; 1 2 3]
if ismatrix(curstate)
    disp('yes');

else
   disp('no') 
end  
end

But it founds the matrix multiple times.

yes
yes
yes

How to check it by the way?

Upvotes: 1

Views: 41

Answers (2)

Matt
Matt

Reputation: 2802

It really depends on what you define a matrix to be. In MathWorks case they decided that a matrix would be something with a valid size, which is certainly true. Notice that even scalars are matrices, of size 1x1. You can even have a matrix of characters. A = ['a' 'b';'c' 'd'];. I gather that in your case you want a matrix to be a numerical collection of at least 2 dimensions. I would solve it this way:

function result = TestForMatrix(m)
    t1 = isnumeric(m);
    t2 = ~isvector(m);
    result = all([t1 t2]);
end

Use it as if it was ismatrix.

if (TestForMatrix(curstate))
    disp('yes');
else
    ....

The way this works is the test for numerical numbers will eliminate character strings. The second test will eliminate vectors and scalars. As you find more things to include or eliminate you add those tests. For example, say you want to allow cells. t3 = iscell(m); result = all([t1 t2 t3]); The are many logical tests that can be done on Matlab objects, see Matlab is*.

Upvotes: 1

marcoresk
marcoresk

Reputation: 1965

From Matlab help:

ismatrix(M) returns logical 1 (true) if SIZE(M) returns [m n] with nonnegative integer values m and n, and logical 0 (false) otherwise

so I checked size(curstate)

1 3 % 3 character string array
1 1 % of course you can do size of a single elements
2 3

so I modified your code

for k=1:length(mixed_values)
  curstate=mixed_values{k};

    % Check for the [5 2 1; 1 2 3]
    if (size(curstate,1)) > 1 && (size(curstate,2)) > 1 
        disp('yes');
        disp(size(curstate));

    else
       disp('no') 
    end  
end

Upvotes: 1

Related Questions