Confusion about elseif statements
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Tim Robinson
am 25 Okt. 2020
Bearbeitet: Tim Robinson
am 25 Okt. 2020
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!
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 25 Okt. 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 Kommentar
Weitere Antworten (1)
KSSV
am 25 Okt. 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 Kommentare
KSSV
am 25 Okt. 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.
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!