how to make a function that discreminate between scalar and vectors in matlab

5 次查看(过去 30 天)
Hi; I am going to make a function that classify inputs.If the input is a vector it generate 0 and if it is empty scalar matrix it gives -1 and for matrix it gives 1 I am using that codes
function myclass=classify(x)
if size(x)==0 0
myclass=-1;
elseif size(x)~=0 0
myclass=1;
end
end
This codes run perfectly for empty matrix and matrix but i getting in troble how i can define it to discriminate for vector(having 1 row or col). I hope i have to use two more ifs in elseif one will check for vector and other for matrix. I stuck how it implement .Kindly guide me about correction..Thanks in advacne
  2 个评论
Muhammad Usman Saleem
This codes run perfectly for empty matrix and matrix but i getting in troble how i can define it to discriminate for vector(having 1 row or col). I hope i have to use two more ifs in elseif one will check for vector and other for matrix. I stuck how it implement .Kindly guide me about correction..Thanks in advacne
Stephen23
Stephen23 2015-5-20
编辑:Stephen23 2015-5-20
What exactly is an "empty scalar matrix"? By definition a scalar is a 1x1 array, and thus cannot be empty. This is clearly documented here:
In any case, what is wrong with the inbuilt functions: isempty, isscalar, isvector, ismatrix, isrow, iscolumn... ? Did they stop working?
Maybe reading this would help:

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2015-5-20
You need to use the any and all functions in your comparisons:
function myclass=classify(x)
myclass = 0;
if any(size(x)==0)
myclass=-1;
elseif all(size(x)>1)
myclass=1;
end
end
This worked for me.
  10 个评论
Muhammad Usman Saleem
tell me where is the problem with my code.Kindly read the question mentioned above to better understand the problem..Thanks in advance
Star Strider
Star Strider 2015-5-20
If it’s a scalar, all dimensions have to be equal to 1, so this statement has to test for that:
elseif all(size(x)>1)
See if substituting the ‘double equal sign’ == helps.
Also, your default condition needs to be set to be sure it returns the correct value as described in: ‘Finally, if x is none of these, it returns 2.’

请先登录,再进行评论。

更多回答(2 个)

Thorsten
Thorsten 2015-5-20
编辑:Thorsten 2015-5-20
You should use Matlab's functions for your task: isempty, isscalar, ismatrix. Further, classify is a function in the statistics toolbox; you may want to choose a different name.

Stephen23
Stephen23 2015-5-20
编辑:Stephen23 2015-5-20
This would be much simpler code without the if commands, even as an anonymous function:
>> fun = @(x) all(size(x)>1)-isempty(x);
>> fun([])
ans =
-1
>> fun([1,2,3])
ans =
0
>> fun([1,2,3;4,5,6])
ans =
1
To do the whole thing without "inbuilt functions" then just replace the isempty(x) with any(size(x)==0). I doubt that any solution fulfills this though:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by