About timer object and StartFcn
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
What does the @(x,y) mean in this phrase: t = timer('TimerFcn',@(x,y)disp('Hello World!'),'StartDelay',5);
0 comentarios
Respuestas (1)
Walter Roberson
el 29 de En. de 2016
The great majority of callbacks in MATLAB are called with two automatically supplied arguments.
The first argument is the handle to the object which the callback is about; this allows you to use the same callback function for multiple objects and still reference the appropriate object.
The second argument is either empty (most common) or a struct . The content of the struct will provide details about what triggered the callback. For example KeyPressFcn callbacks get an event structure that indicates which key was pressed.
It happens that the timer object callbacks never need to be passed additional information of this sort, so for them the second parameter is always empty, [] . MATLAB provides the argument even if it is empty in order to provide a uniform interface. It is not required that you do anything with either parameter.
(The exception to this organization are the few "callbacks" that are used as filters, such as position constraint functions and datacursormode datatip construction functions; these few functions return values whereas regular callbacks that follow the standard scheme never return values.)
3 comentarios
Walter Roberson
el 29 de En. de 2016
"Why do we use @(x,y)"
Arbitrary dummy parameter names. It would have meant the same thing to write @(source,event) or @(hObject,evt) .
In the case where the parameters are being ignored, @(~,~) is fine too. It is just a newer syntax not supported by sufficiently old MATLAB. There hasn't been any point in going back to edit the examples to use ~
Guillaume
el 30 de En. de 2016
Editada: Guillaume
el 30 de En. de 2016
Calling the callback arguments x and y is very silly. Using variable names that represent what they actually contain is a big aid in making the program easy to understand.
In many languages, .Net in particular, there is always two arguments for an event ( == callback), the source that generated the event and an object that represent the event properties (coordinates for a mouse click, key pressed for a key event, etc.).
Matlab follows the same pattern except that often it actually doesn't put anything in the event property (a wasted opportunity if you ask me).
If you are not going to ignore the event arguments (with @(~, ~)), I'd recommend you call them source and eventargs. That is the convention in many other languages.
Ver también
Categorías
Más información sobre Interactive Control and Callbacks en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!