Function handle in structure field generating data from other fields
显示 更早的评论
Hi everyone,
I have a structure and in one of its fields I want to store some data. It is large data, but generation of it is very fast. Since the structure needs to be saved as matfile, generating the data when needed (i.e. when accessing the struct field) would be much better than storing it with the struct. Is this possible to solve this, maybe with function handles?
Lets assume a function
function[DataOut]=MyFunction(Locs, Peaks)
% some random stuff happening to generate DataOut
end
and a struct with the fields
MyStruct.Locs=[1 3 5 7 9];
MyStruct.Peaks=[40 50 60 70 80];
MyStruct.ProcessedData=@MyFunction
Is is somehow possible to just access the field MyStruct.ProcessedData and to get the data that have been produced by using the fields "MyStruct.Locs" and MyStruct.Peaks" ? That means that I would have to tell the function handle which data to use when making the handle... But how?
I think this is close to something like object oriented programming and a special method invoked when trying to access a field. But I have not much knowledge about this kind of topics. You help is very much appreciated!
Thanks in advance!
6 个评论
Guillaume
2019-4-8
Things to bear in mind if you save a function handle in a mat file:
- When you load the mat file, the function that handle points to must be on the path.
- If a different function with the same name is on the path when you load the mat file, that function will be called instead.
Instead of a function handle, you could store an anonymous function. Variables in scope are permanently bound to an anonymous function when it is created. e.g:
a = 5;
b = 3;
fh = @(x) a+x-b;
fh(1) %return 3
%at this point a and b are bound to the anonymous function.
%changing their value does not affect the anonymous function
a = 0;
b = Inf;
fh(1) %still return 3
%even deleting them does not affect the anonymous function
clear a b
fh(1) %still return 3
Whether or not that can work for you, I'm not sure. It really depends on what the inputs to your function are.
Maximilian Rüppell
2019-4-8
Steven Lord
2019-4-8
It sounds to me like you want an object instead of a struct with a function handle as one of its fields. The function would then become an instance method of the class (not a Static method) and as such would need to be called with an instance of the class as one of its inputs.
Guillaume
2019-4-8
So I'm a bit unclear on what you are trying to do. In the mat file, do you want to store:
- all the required inputs necessary to recreate the missing data as fields of the structure
or
- somehow, a function that recreates the missing data, without explicitly storing the data as fields of the structure?
Maximilian Rüppell
2019-4-8
Maximilian Rüppell
2019-4-8
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Common Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!