Changing the number of input arguments while calling a function in a loop
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 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.
Weitere Antworten (1)
Teja Muppirala
am 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!