Writing a function handle in a for loop

9 visualizzazioni (ultimi 30 giorni)
Mehmet Velioglu
Mehmet Velioglu il 21 Dic 2018
Commentato: dpb il 22 Dic 2018
Hello everybody,
As you can see below I want to create a function handle temp_control, however x(1),x(2),x(3) and given control has different permutations in different cases. So rather than writing it manually as below; ( given_control is a number)
temp_control = @(x) [given_control,x(1),x(1),x(2),0,0,0,x(3),0]';
temp_control = @(x) [x(1),given_control,given_control,x(2),0,0,0,x(3),0]';
temp_control = @(x) [x(1), x(2), x(2), x(3), 0, 0, 0, given_control, 0]';
temp_control = @(x) [x(1),x(2),x(2),given_control,0,0,0,x(3),0]';
I want to put x(1), x(2) and x(3) to the function handle temp_control, in a for loop. I want this for loop to handle the permutation. The function handle is used later in fminsearch.
fun = @(x) OP_residual(aircraft,ASZ,phi,theta,temp_control(x));
[x_out,residiual] = fminsearch(fun,x_in);
I have piece of code to try this;
id = 8; %can be 1,2,4,8
possible_givens=[1,2,4,8];
possible_givens = possible_givens(possible_givens~=id);
temp_control = cell(1,9);
for j=1:length(possible_givens)
temp_control{possible_givens(j)} = sprintf('x(%d)',j);
end
temp_control {3} = temp_control{2};
temp_control{id} = num2str(given_control(id));
temp_control = str2func(temp_control);
Obviously str2func doesnt work. I cannot solve the problem. Would appreciate if someone can help :)
  4 Commenti
dpb
dpb il 21 Dic 2018
The key is you have to have a definible logic that can be turned into an algorithm that determines how many and what is the Nth argument of the proposed anonymous function.
I can't tell what is behind the examples at the beginning from which to be able to code the elements. Given that, writing a string expression to pass to str2func would be essentially a trivial exercise.
dpb
dpb il 22 Dic 2018
OK, I studied the pattern in the initial example a little more...looks like the easiest way to implement this would be to store the pieces in a cellstr() array and use some logic to index the order of putting the pieces together based on that position. The kicker that I don't quite see the actual logic behind is which index is to be the repeated one based on the examples, but I didn't have a terribly long time to study it.
If these are the only four cases, in reality probably the best choice is to just store the precise functions in a function handle array and index into that array based on the case in hand--if there's a dynamic into the order or the index of which is the repeated element that is variable, then the need for the algorithm comes back into play.

Accedi per commentare.

Risposte (0)

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by