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

조회 수: 4 (최근 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