How do you check if an inputed number is an array/vector or just 1 value?

Using function [a, b, c, d] = function_name(a,b,c,d)
I know that if it's an array, [] will be used in the input and the script will have to call a position of an array eg. y(1) or y(2)
If it's a discrete value it will just be y
Basically, instead of calling 1 value of a, i want to call 2 or more, etc
I don't know if that makes any sense, but it would be very helpful if someone could please just help me out.

 採用された回答

Andrew Newell
Andrew Newell 2014 年 4 月 25 日
You can use size to find the number of components in each variable, e.g.:
size(a)

その他の回答 (2 件)

Star Strider
Star Strider 2014 年 4 月 25 日
編集済み: Star Strider 2014 年 4 月 25 日
If you want to check whether a particular argument is a scalar (single-value) or an array, use the size function:
[r,c] = size(x)
if (r > 1) | (c > 1)
xscalar = 0;
else
xscalar = 1;
end
Then you can treat it as a vector later in your code if xscalar = 0 or a scalar if xscalar = 1.

3 件のコメント

Madeleine
Madeleine 2014 年 4 月 25 日
Thankyou very much :)
Star Strider
Star Strider 2014 年 4 月 25 日
My pleasure!
giannit
giannit 2021 年 4 月 12 日
You can do it in one line
xscalar = isscalar(x)

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

Rik
Rik 2021 年 4 月 12 日
In my view using numel or isscalar (introduced somewhere between v6.5 and v7.1) would be a better solution.
xscalar = numel(x)~=1;
xscalar = isscalar(x);
That way you can avoid size. numel is useful if you have old releases to consider, but otherwise isscalar should work just fine.

カテゴリ

質問済み:

2014 年 4 月 25 日

回答済み:

Rik
2021 年 4 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by