MATLAB: Subset of varargin as function input

matlab functionvarargin

I call a function in the main code
plotFT( var1,var2,...,var13)
whose input variable can be either 10 or 13. The function in subject is defined as follows:
function plotFT( varargin )
switch nargin
case 10
fun1( varargin{1:10} ) %why doesn't work just with varargin as input?
case 13
subplot(1,2,1)
fun1( varargin{1:10} )
subplot(1,2,2)
fun2( [ varargin{1:3} varargin{11:13} ] ); %I can't't catch the mistake
otherwise
warning('Unexpected number of inputs')
end
fun1 works but for fun2 the followinf error message is prompted: "Error using horzcat. The following error occurred converting from char to struct: Conversion to struct from char is not possible." Questin1:

Best Answer

Try this:
function plotFT(varargin)
switch nargin
case 10
fun1(varargin{:})
case 13
subplot(1,2,1)
fun1(varargin{1:10})
subplot(1,2,2)
fun2(varargin{[1:3,11:13]});
otherwise
warning('Unexpected number of inputs')
end
"why doesn't work just with varargin as input?"
Because varargin is one cell array. If fun1 expects ten separate inputs, then you cannot just pass it one cell array. The syntax cellarray{...} generates a comma-separated list, which is equivalent to writing each cell as its own input argument, like this:
fun1(varargin{1}, varargin{2}, ... )
To learn more about comma-separated lists read this explanation:
"I can't't catch the mistake"
Because you try to concatenate the contents of varargin together, which clearly does not make sense for your input arrays, because they are different classes/sizes/...
After reading the links I gave you, you will know that your code
[ varargin{1:3} varargin{11:13} ]
is exactly equivalent to this
[varargin{1},varargin{2},varargin{3},varargin{11},varargin{12},varargin{13}]
Is there much point in concatenating all of them together? I doubt it. Most likely you want them as separate inputs, which, after reading the links I gave you, you will know that you can achieve using either of these two syntaxes:
fun2(varargin{[1:3,11:13]})
fun2(varargin{1:3},varargin{11:13})
both of which are equivalent to writing
fun2(varargin{1},varargin{2},varargin{3},varargin{11},varargin{12},varargin{13})
which I suspect is what you were trying to achieve (although you do not actually specify anything about fun2 in your question, such as how many inputs it requires, so I had to guess).