Can I store and call functions from within a struct?

Hi everyone,
i want to create a struct with the following fields: analysis(i).type (this is a list of different types of possible analysis) analysis(i).function (this should contain the specific function that should be executed, if a specific type of analysis was chosen)
I've tried some things so far, but nothing worked...so i'm wondering if this is even possible?
Thank you!

 Respuesta aceptada

Stephan
Stephan el 3 de Sept. de 2018
Editada: Stephan el 3 de Sept. de 2018
Hi,
you can store function handles in a struct and use them like this:
fun1 = @(x,y) x + y
fun2 = @(x,y) x - y
analysis.add = fun1
analysis.subtract = fun2
res1 = analysis.add(1,2)
res2 = analysis.subtract(5,3)
Best regards
Stephan

4 comentarios

Or assigning directly:
analysis.add = @(x,y) x + y
analysis.subtract = @(x,y) x - y
Stephan
Stephan el 3 de Sept. de 2018
Editada: Stephan el 3 de Sept. de 2018
@Stephen you are always one step ahead ;-)
And if the function to execute is a m file (as opposed to anonnymous functions in Stephan and Stephen's example), then:
%store function handle to m file myfunc.m:
analysis.add = @myfunc
Julian
Julian el 3 de Sept. de 2018
Thank you guys :)

Iniciar sesión para comentar.

Más respuestas (1)

Hank
Hank el 1 de Mayo de 2019
Editada: Hank el 1 de Mayo de 2019
To further this question, I would like to use fields of the struct as parameters in the functions, hopefully without having to write an entire class for this purpose.
for example
circ = struct('Radius', 3 ,...
'Area', @() pi*Radius^2 );
where 'radius' in the anon function somehow references circ.Radius
Then, radius may be change by other programs or the user action but whenever I access circ.Area, it references the current radius.
Cheers, Henry

4 comentarios

Guillaume
Guillaume el 1 de Mayo de 2019
Can you please start a new question of your own instead of writing it as an answer to somebody else's question?
Hank
Hank el 1 de Mayo de 2019
Sure thing. Sorry, but it seemed like a related-enough addendum.
Guillaume
Guillaume el 1 de Mayo de 2019
You can link to this question in your own. We can't answer an Answer, only comment on it. You can't accept a comment as resolving a question asked in an answer.
Hank
Hank el 1 de Mayo de 2019
Fair enough. I think I've resolved that this can only be acheived by creating a class for the object i'm interested. There's no support of methods for a struct.

Iniciar sesión para comentar.

Categorías

Más información sobre App Building en Centro de ayuda y File Exchange.

Productos

Versión

R2018a

Preguntada:

el 3 de Sept. de 2018

Comentada:

el 1 de Mayo de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by