Storing the inputs of a function on a structure (or cell or array)

given a function such as:
function [z,w] = tempFun(x,y)
z = x+1;
w = y+1;
end
is it possible to store a given pair x,y as a structure (struct('x',1,'y',2), say, or as a cell or anything else...) and then unpack it and apply the function to the output?
(In python this could be done as: temFun( **{'x':1, 'y':2})

 採用された回答

madhan ravi
madhan ravi 2019 年 8 月 15 日

0 投票

d=struct('x',1,'y',2);
[z,w] = tempFun(d)
function [z,w] = tempFun(s)
z = s.x+1;
w = s.y+1;
end

6 件のコメント

James Otterson
James Otterson 2019 年 8 月 15 日
Thanks for your reply, my problem is that I cannot change tempFun itself.
I guess, following your line of argument, my option is to create something like
function [z,w] = tempFun2(d)
tempFun(d.x, d.y)
end
madhan ravi
madhan ravi 2019 年 8 月 15 日
Why not
x=1;
y=2;
[z,w] = tempFun(x,y)
function [z,w] = tempFun(x,y)
z = x+1;
w = y+1;
end %??
madhan ravi
madhan ravi 2019 年 8 月 15 日
Or perhaps you want to take advantage of comma separated list?
d = {x,y};
[z,w] = tempFun(d{:})
James Otterson
James Otterson 2019 年 8 月 15 日
That's exactly it, thanks a lot!
James Otterson
James Otterson 2019 年 8 月 15 日
(the only slight upper hand the python code above has over this is that it will map the variables to their righ places, ie. you won't need to store then in the right order:
tempFun( **{'x':1,'y':10}) == tempFun(**('y':10,'x':1})
madhan ravi
madhan ravi 2019 年 8 月 15 日
編集済み: madhan ravi 2019 年 8 月 15 日
Well, I'm a beginner in python (didn't get to this point still) , but this topic would be interesting to be debate about. But then do not underestimate the power of MATLAB ;-)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

質問済み:

2019 年 8 月 15 日

編集済み:

2019 年 8 月 15 日

Community Treasure Hunt

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

Start Hunting!

Translated by