Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to write some code which feeds a function with an unknown number of parameters. The idea is to feed the function the minimum, middle and maximum value within the possible range of values.

For example:

  • If the function takes 3 parameters
  • Parameter 1 can accept a range of 0 - 10
  • Parameter 2 can accept a range of 20 - 40
  • Parameter 3 can accept a range of 6 - 66

myfunction(para1, para2, para3)
myfunction(min,min,min)
myfunction(min,min,mid)
myfunction(min,min,max)
myfunction(min,mid,min)
myfunction(min,mid,mid)
myfunction(min,mid,max)
etc...

so using our example above:

The first time it loops I need to run
myfunction(0, 20, 0)
next time it loops it needs to run
myfunction(0, 20, 36)
next time it loops it needs to run
myfunction(0, 20, 66)
etc...

For all possible combinations (in this case all 27).
However, if the number of parameters changes to accept 4, it needs to be able to accommodate that and so on. I've looked into doing it as a loop or recursively, but I thought as a loop would be easier to understand, but either would be really helpful.

I don't want to have to do this manually so any help will be much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
905 views
Welcome To Ask or Share your Answers For Others

1 Answer

Think about something like this:

function result = permfunction() 

% I assume you every parameter-range is defined by 3 values: min, mid, max
% you can define every triple as follows:
para1 = linspace(0,10,3);
para2 = linspace(20,40,3);
para3 = linspace(6,66,3);

% all possible parameters
parameters = [para1(:),para2(:),para3(:)];

% possible combinations of parameters-indices
a = perms(1:3);  
% transformed into a cell array with linear indices, to achieve this +3 and +6 
% are added to the 2nd and 3rd row.

idx = mat2cell( [a(:,1) , a(:,2)+3 , a(:,3)+6] , ones(length(a),1) );

% all parameter combinations
combinations = cellfun(@(x) parameters(x),idx,'uni',0');

% apply to your function myfunction (custom)
result = cellfun(@myfunction, combinations,'uni',0' );

end

function y = myfunction( parametertriple )

%just pass the input to the output
y = parametertriple;

end

you finally get a cell array with the results of myfunction for all your combinations of parameters. In this case I just passed the parameters to the output:

>> celldisp(ans)

ans{1} =

    10    30     6

ans{2} =

    10    20    36

ans{3} =

     5    40     6

ans{4} =

     5    20    66

ans{5} =

     0    30    66

ans{6} =

     0    40    36

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...