## Various inputs and outputs in functions

Jason

### Jason (view profile)

さんによって質問されました 2017 年 9 月 9 日

### José-Luis (view profile)

さんによって 編集されました 2017 年 9 月 9 日
KSSV

### KSSV (view profile)

さんの 回答が採用されました
Hi. I have several techniques to find spots on an image and rather than have say 5 different functions I want to create one and pass in a "method" flag. My question is that each different method has a different number of inputs and outputs. Im not sure how to handles these, and help is greatly appreciated.
function[p1,p2,p3,p4,p5]=objectDetections(handles,image,x,y,par1,par2,method)
if method==1
//perform method 1 - requires inputs handles,image,x,y
// returns p1,p2
elseif method==2
//perform method 2 - handles,image,x,y, par1
//returns p1,p3
elseif method==3
//perform method 3 - handles,image,x,y, par1, par2
//returns p1,p2,p3,p4,p5
end

#### 1 件のコメント

Stephen Cobeldick

### Stephen Cobeldick (view profile)

2017 年 9 月 9 日
The simplest, clearest, neatest solution: use a structure. This is what MATLAB uses for many advanced functions that support multiple options, (e.g. optimization, ODE's, etc), and is simple to implement.

サインイン to comment.

## 2 件の回答

2017 年 9 月 9 日

### KSSV (view profile)

2017 年 9 月 9 日
採用された回答

You have multiple options...one of the option is make output a structure....
function[out]=objectDetections(handles,image,x,y,par1,par2,method)
if method==1
//perform method 1 - requires inputs handles,image,x,y
out.p1 = p1;
out.p2 = p2;
elseif method==2
//perform method 2 - handles,image,x,y, par1
out.p1=p1;
out.p3=p3;
elseif method==3
//perform method 3 - handles,image,x,y, par1, par2
out.p1=p1;
out.p2=p2;
out.p3=p3;
out.p4=p4;
out.p5=p5;
end
You can also make output a cell.

Jason

### Jason (view profile)

2017 年 9 月 9 日
Thats a nice idea. What about for the input arguments, for example method 1 doesn't require par1 or par2, can I just use a ~ i.e.
objectDetections(handles,image,x,y,~,~,method) or is there a nicer way?
Thanks
KSSV

### KSSV (view profile)

2017 年 9 月 9 日
Input also can be made a structure
Jason

### Jason (view profile)

2017 年 9 月 9 日
Thankyou

サインイン to comment.

2017 年 9 月 9 日

### José-Luis (view profile)

2017 年 9 月 9 日

You could pass a structure to your function. The structure could contain whatever flags and arguments you need. Same goes for the output.
Slightly more cumbersome: a function can accept a variable number of arguments -> varargin

#### 0 件のコメント

サインイン to comment.

Translated by