Pointer to MATLAB function?

조회 수: 95 (최근 30일)
Kalamaya
Kalamaya 2012년 8월 29일
So I have a for-loop in MATLAB, where either a vector x will be put through one function, say, cos(x).^2, or a different choice, say, sin(x).^2 + 9.*x. The user will select which of those functions he wants to use before the for-loop.
My question is, I dont want the loop to check what the user selected on every iteration. Is there a way to use a pointer to a function, (user defined, or otherwise), that every iteration will use automatically?
This is inside a script by the way, not a function.
Thanks

채택된 답변

Oleg Komarov
Oleg Komarov 2012년 8월 29일
An interactive way to create an anonymous function:
% List of functions
funs = {'cos(x).^2','sin(x).^2 + 9.*x'};
% Ask for the function through a dialog
[idx,ok] = listdlg('ListString' ,funs,...
'PromptString' ,'Select one function',...
'SelectionMode','single');
% Convert to anonymous function
if ok
f = str2func(sprintf('@(x)%s', funs{idx}));
end

추가 답변 (3개)

José-Luis
José-Luis 2012년 8월 29일
편집: José-Luis 2012년 8월 29일
I am not entirely sure this is what you mean but here goes:
if (first_selection)
fun1 = @(x) cos(x).^2;
end
if (second_selection)
fun1 = @(x) sin(x).^2 + 9 .* x;
end
And now your loop:
for k = 1:num_Loops
x = your_values;
your_result = fun1(x);
end
Cheers!

owr
owr 2012년 8월 29일
Do a search in the docs on function handles. They should do the trick.
  댓글 수: 1
owr
owr 2012년 8월 29일
Loren just wrote a nice blog post that might be helpful as well:

댓글을 달려면 로그인하십시오.


Ghada
Ghada 2012년 11월 12일
Hi all;
please i need an example of the application of iteration in ananymous function,
Awaiting to you response,
Best regards,
my mail is :chahd.hayet@gmail.com

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by