Confusion about elseif statements

1 view (last 30 days)
I would like to generate code that decerns between input types scalar, vector (row or column), or matrix. I have written the following code:
function output = findtype(input);
[r c] = size(input);
if r == 1 && c == 1
output = 'scalar';
elseif r == 1 || c == 1
if r == 1
output = 'row vector';
else
output = 'column vector';
end
else
output = 'matrix';
end
end
When I enter findtype(3), the code correctly returns 'scalar'. Likewise, when I enter findtype(ones(5,3)), the code correctly returns 'matrix'. However, when I enter any type of vector, whether it is findtype(1:5), findtype(5:1), or findtype (2:3), the code returns 'row vector'. It seems to me that in the second instance, the elseif statement should be true (since c = 1) and the if statement that follows should be false, since r ≠ 1, so the code should return 'column vector'. In the final instance, it seems the code should return 'matrix', since neither r nor c are equal to 1. I am confused as to why I am getting these results for vector inputs. Can someone help me understand where I've made an error? Thank you!

Accepted Answer

Walter Roberson
Walter Roberson on 25 Oct 2020
c will not be 1 for size([1:5]) . When you use the colon operator, the result is always a row vector, never a column vector.
Remember you are passing in the data whose size is to be checked, rather than passing in size information.
By the way, I recommend that you think more about how you want to handle empty values.
  1 Comment
Tim Robinson
Tim Robinson on 25 Oct 2020
Edited: Tim Robinson on 25 Oct 2020
Yes, this was a very basic misunderstaninf on my part. Thank you for pointing this out. I checked my function with findtype(rand(10, 1)) and it works.

Sign in to comment.

More Answers (1)

KSSV
KSSV on 25 Oct 2020
The function is fine...there is one typo error..... you should use '=' not '=='
function output = findtype(input);
[r c] = size(input);
if r == 1 && c == 1
output = 'scalar';
elseif r == 1 || c == 1
if r == 1
output = 'row vector';
else
output = 'column vector';
end
else
output = 'matrix';
end
end
  3 Comments
KSSV
KSSV on 25 Oct 2020
For that case, he can modify the line:
[r c] = size(input);
to
[r, c,d] = size(input);
He can follow the same check with r, c and make a new check with third dimension if he wants. As OP not mentioned about 3D arrays....I have not thought about that.
Tim Robinson
Tim Robinson on 25 Oct 2020
Thank you! I used = instread of == in my orginal function, but in my haste, I mistyped the function. I had not considered 3D arrays, but thank you for the suggestion!

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!