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
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 个评论
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
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 个评论
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 个)
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:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Classification Trees 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!