Changing the number of input arguments while calling a function in a loop

4 views (last 30 days)
Very briefly, I have a for loop of the form:
for i=1:30
out=myfun(X, in1, in2, ... , inN);
end
myfun takes as input arguments a matrix X and can take upto N vectors after that. What I want to do is, give as input:
out=myfun(X, in(1,:)); %when i=1
out=myfun(X, in(1,:), in(2,:)); %when i=2
out=myfun(X, in(1,:), in(2,:), in(3,:)); %when i=3
... and so on..
So for every iteration of the loop, the number of input arguments will increase, and I could not find a way to do this except manually. (And I don't want to manually enter the lines above for 100 different input arguments.)
The only things I could think of doing until now are using string arrays or cell arrays whose size will increase at every iteration but what I want to give as input to myfun() is not a string but a variable name. I have no idea how matlab handles this, and any replies would be greatly appreciated.

Accepted Answer

Walter Roberson
Walter Roberson on 23 Jan 2012
Put the vectors in a cell array, say Cin, and then
out = myfun(X, Cin{1:N});
However, if you really need to pass in variable names then this will not work for you; inputname() will return empty because these would be expressions instead of variables. If you really need to pass in variable names instead of values, you should explain more about why passing in names is important to your purposes.
  1 Comment
sirona
sirona on 23 Jan 2012
Sorry for the confusion, this was exactly what I needed. I am not very familiar with cell arrays myself so I couldn't figure out the syntax I guess. Thanks for your help.

Sign in to comment.

More Answers (1)

Teja Muppirala
Teja Muppirala on 23 Jan 2012
The cell array as mentioned above is a reasonable approach. Another possibility would be to modify your function so that the function would recieve the whole matrix "in", along with the index, and then myfun can take care of getting the appropriate rows on its own. Thus your loop would look like this:
for k = 1:30
out = myfun(in, k)
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!