How to restrict input to set of sizes in an arguments block?

3 ビュー (過去 30 日間)
Andreas Urbán
Andreas Urbán 2022 年 3 月 18 日
回答済み: Steven Lord 2022 年 3 月 18 日
I have a function with argument that should be either 2 x N or 3 x N size. Can't seem to figure out how to have that in an input block. Something similar to below (which isn't supported syntax):
arguments
myArg (2:3,:);
end

採用された回答

Steven Lord
Steven Lord 2022 年 3 月 18 日
I don't believe you can do this with the dimension validation alone. Nor would the existing validation functions help. So you're going to need to write your own, which I've done below as mustHaveTwoOrThreeRows. These first two cases work:
sample1674659(ones(2, 3))
ans = 6
sample1674659(ones(3, 3))
ans = 9
Specifying an input with the wrong number of rows will error, as will specifying an N-dimensional array (N > 2) (because of the dimension validation.)
try
sample1674659(ones(4, 3))
catch ME
fprintf("This case threw the error:\n\n%s\n", ME.message)
end
This case threw the error: Invalid argument at position 1. X must have either two or three rows.
try
sample1674659(ones(2, 3, 4))
catch ME
fprintf("This case threw the error:\n\n%s\n", ME.message)
end
This case threw the error: Invalid argument at position 1. Value must be a matrix.
function y = sample1674659(x)
arguments
x (:, :) {mustHaveTwoOrThreeRows(x)}
end
y = sum(x, 'all');
end
function mustHaveTwoOrThreeRows(x)
s = size(x, 1);
if ~(s == 2 || s == 3)
error('X must have either two or three rows.');
end
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeIntroduction to Installation and Licensing についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by