A function with 2 inputs, how to make it accept a 2-by-1 array as an input?

Hi all,
There are some functions which accepts 2 inputs, such as inpolygon. For example:
K>> xv
xv =
1
2
2
1
K>> yv
yv =
1
1
2
2
K>> x = 1.5
x =
1.5000
K>> y = 1.5
y =
1.5000
K>> inpolygon(x, y, xv, yv)
ans =
logical
1
Which is completely fine. However, if I have an array which contains x-y coordinates, such as:
K>> xy = [1.5 1.5]
xy =
1.5000 1.5000
How can I use xy as an input instead of using x and y separately? I do not want to extract x and y manually like:
K>> x = xy(1), y = xy(2)
I want something like:
K>> inpolygon(xy, x, y)
Not enough input arguments.
Error in inpolygon (line 64)
if ~isvector(xv) || ~isvector(yv)
but there is error. Any ideas?

 채택된 답변

KSSV
KSSV 2017년 11월 13일
function out = myinpolygon(xy,x,y) ;
out = inpolygon(xy(:,1),xy(:,2),x,y) ;
end
:)

댓글 수: 6

Xiaohan Du
Xiaohan Du 2017년 11월 13일
편집: Xiaohan Du 2017년 11월 13일
I mentioned in the question that manually separate the inputs as xy(:, 1) and xy(:, 2) is not suitable for my problem.
Why not suitable?
Well, you might be able to do this for this function, but for functions with multiple input, it wouldn't be convenient to manually separate in a way of
aFunction(xy(:, 1), xy(:, 2), xy(:,3), ......)
It's better to be able to do something about xy, such that the function becomes:
aFunction(xy)
Similar to function output, if knowing how many outputs there are, we can always put them into one cell, see: https://www.mathworks.com/matlabcentral/answers/366057-how-to-combine-multiple-output-from-a-function-into-1
Stephen23
Stephen23 2017년 11월 13일
편집: Stephen23 2017년 11월 13일
@Xiaohan Du: In much the same way you can put the input arguments into one cell array, then convert this to a comma-separated list when supplying them to the function. I would not recommend doing this as a general way of calling function though, as it obfuscated the code and makes debugging harder.
I see, we can do this:
K>> inpt = {1 2}
inpt =
1×2 cell array
[1] [2]
K>> inpolygon(inpt{:}, xv, yv)
ans =
logical
1
such that only 1 input is needed (of course there are still 2 elements in this input).
Thank you Stephen!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

질문:

2017년 11월 13일

댓글:

2017년 11월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by