How can I implement an array of function handles that takes a struct as input and calculates the function value for each function handle?

조회 수: 2 (최근 30일)
I have function handles, e.g. area_rectangle and area_circle, and structs that contain information like input_variables.height = 3.
function area_rectangle = area_rectangle(input_variables, constants)
if ~isfield(input_variables,'height') || ~isfield(input_variables,'width')
area_rectangle = NaN;
else
area_rectangle = input_variables.width * input_variables.height;
end
function area_circle = area_circle(input_variables, constants)
if ~isfield(input_variables,'radius') || ~isfield(constants,'pi')
area_circle = NaN;
else
area_circle = constants.pi * input_variables.radius^2;
end
Unfortunately, cell arrays can't be used because they need some kind of index support:
>> test = cell(2,1)
test =
[]
[]
>> test{1}=@area_rectangle;
>> test{2}=@area_circle;
>> test
test =
@area_rectangle
@area_circle
>> input_variables = struct('height',3,'width',2,'radius',1)
input_variables =
height: 3
width: 2
radius: 1
>> constants = struct('pi',3.14159)
constants =
pi: 3.1416
>> test(input_variables,constants)
Error using subsindex
Function 'subsindex' is not defined for values of class 'struct'
How can I use function handles and structs at the same time?
Thanks in advance.

채택된 답변

Jan Orwat
Jan Orwat 2015년 6월 2일
Hello Carolin, you can evaluate functions in a loop:
>> values = zeros(1,length(test));
>> for k = 1:length(test)
values(k) = test{k}(input_variables,constants);
end
>> values
values =
6.0000 3.1416
or using cellfun():
>> values = cellfun(@(F)F(input_variables,constants),test)
values =
6.0000 3.1416
cellfun looks more compact, but it is often harder to read and modify, especially when you are going back to the piece of code after a while.
  댓글 수: 1
Carolin Katzschke
Carolin Katzschke 2015년 6월 2일
Hi Jan,
thank you very much for your quick answer. Both possibilities are correct solutions, but for my upcoming work I prefer the second.
Thanks, Carolin

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by