Empty matrix, scalar, or vector function in loop

Greetings all, I need to write a function called CLF whose input argument is x, that input argument must not have more than two dimensions. If x is an empty array, the function returns -1. If x is a scalar, the function returns 0. If x is a vector, the function returns 1 and if x is none of the above, the function returns 2, do not use isempty, isscalar, isvector, my code is as follows: thank you!
function y=CLF(x)
for a=1:n;
if x=[];
y='-1';
elseif x=a;
y='0';
elseif x=[a,a];
y='1';
else x~=a;
y='2';
end
end
end

 Accepted Answer

MATLAB uses == for comparisons, not =
Also,
X = []
X = []
Y = 1
Y = 1
if X == []; disp('X yes 1'); end
if Y == []; disp('Y yes 1'); end
if isequal(X, []); disp('X yes 2'); end
X yes 2
if isequal(Y, []); disp('Y yes 2'); end

6 Comments

And remember that your assignment requires you to return a number not a character !
Thank you very much, that was precisely my big doubt in this question, related to scalar
size([]) %empty
ans = 1×2
0 0
size(ones(0,1)) %empty
ans = 1×2
0 1
size(ones(1,0)) %empty
ans = 1×2
1 0
size(42) %scalar
ans = 1×2
1 1
size([42, 43, 44]) %row vector
ans = 1×2
1 3
size([42; 43; 44]) %column vector
ans = 1×2
3 1
size([2 3 4; 5 6 7]) %2d array
ans = 1×2
2 3
size(ones(1,2,3)) %3d array
ans = 1×3
1 2 3
size(ones(2,3,4)) %3d array
ans = 1×3
2 3 4
size(ones(1,2,3,0,5,6)) %empty 6d array
ans = 1×6
1 2 3 0 5 6
Thank you dear Walter, at this moment I finished my code, but I think I have a problem with the representation of the vector:
function y=wilo(x)
if x==[];
y=-1;
elseif isequal(x,[]);
y=-1;
elseif x==x+1;
y=0;
elseif x==[x,x];
y=1;
elseif isequal(x,[x,x]);
y=1;
else any((x~='[]')&(x~='x+1')&(x~='[x,x]'));
y=-2;
end
end
I missed a case in my examples:
isequal([], ones(1,2,3,0,5,6))
ans = logical
0
That tells you that you cannot use isequal() to generally detect empty matrices.
elseif x==x+1;
The only case that would match that would be if x consists of all infinite values (positive or negative)
elseif x==[x,x];
[x,x] is going to have more elements than x does, except in the case that x is empty. However we already showed that you cannot use == to test for empty.
You should be examining size(x) rather than any of the tests you are presently doing.
Thank you dear friend!

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!