MATLAB: Vector/martix limit size

if statementvector

Hi
I not sure what I have done wrong basically the above if statement make sure the values in vector is desire number and if this above equation is correct the below is executed to make sure vector is 1×3 but if vector is same dimension it will give an output number if not it should go else. I am pretty sure above equation is correct but is this right way or is there another method?
elseif all([1,3]) == size(v)
answer = 1;
else
answer = 0;

Best Answer

Your code is buggy, and that concept will fail for 3D arrays. Try this instead:
isrow(v) && numel(v)==3
OR
isequal(size(v),[1,3])
Lets look at the bug in your code. First note that the LHS will always be true, as no value is zero:
>> all([1,3])
ans = 1
So the LHS is always equal to 1, which you then compare against the size of v:
>> v = 1:4;
>> all([1,3])==size(v)
ans =
1 0
>> 1==size(v) % exactly equivalent

ans =
1 0
this will never be all true (which if requires if the condition is non-scalar), unless v is a scalar:
>> v = 4;
>> all([1,3])==size(v)
ans =
1 1
>> 1==size(v) % exactly equivalent
ans =
1 1
The error was putting the parenthesis in the wrong place, it should have been right at the end:
all([1,3]==size(v))
but note that this will still fail for ND arrays. The code at the top of this answer will work for any size array.
Related Question