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

2 次查看(过去 30 天)
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.

采纳的回答

Walter Roberson
Walter Roberson 2012-1-23
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 个评论
sirona
sirona 2012-1-23
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.

请先登录,再进行评论。

更多回答(1 个)

Teja Muppirala
Teja Muppirala 2012-1-23
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by