Confusion about elseif statements

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!

 Risposta accettata

Walter Roberson
Walter Roberson il 25 Ott 2020

0 voti

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 Commento

Tim Robinson
Tim Robinson il 25 Ott 2020
Modificato: Tim Robinson il 25 Ott 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.

Accedi per commentare.

Più risposte (1)

KSSV
KSSV il 25 Ott 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 Commenti

The function is not completely fine. Consider
findtype(rand(4,2,2))
findtype(rand(4,2,0))
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.
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!

Accedi per commentare.

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by