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!

 採用された回答

Walter Roberson
Walter Roberson 2020 年 10 月 25 日

0 投票

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 件のコメント

Tim Robinson
Tim Robinson 2020 年 10 月 25 日
編集済み: Tim Robinson 2020 年 10 月 25 日
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.

サインインしてコメントする。

その他の回答 (1 件)

KSSV
KSSV 2020 年 10 月 25 日

0 投票

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 件のコメント

Walter Roberson
Walter Roberson 2020 年 10 月 25 日
The function is not completely fine. Consider
findtype(rand(4,2,2))
findtype(rand(4,2,0))
KSSV
KSSV 2020 年 10 月 25 日
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 2020 年 10 月 25 日
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!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2020 年 10 月 25 日

編集済み:

2020 年 10 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by