How can I write the arguments of an anonymous function when programming?

4 ビュー (過去 30 日間)
Piockñec
Piockñec 2014 年 4 月 17 日
コメント済み: per isakson 2014 年 4 月 18 日
Good afternoon, my question arises when trying to programme the following code:
s(i+1)=NRK(Dt*f(tv(i+1),x)+s(i)-x,s(i));
Where NRK=NRK(function , numeric scalar) This was the symbolic implementation, with f=symbolic function, and x a symbolic array of unknowns.
The thing is that working with symbolic expressions can solve the issue, but this goes inside a loop, and symbolic tools slow down suprisingly the performance in a ratio of 100 times! However, anonymous functions do a perfect job.
My try was the following:
h=@([arguments (i.e. a, b, c, ...])Dt*f(t(i+1),[arguments (i.e. a, b, c,...])+s(i)-[a b c ...];
s(i+1)=NRK(@h,s(i));
How can I write these arguments? Is it possible? Thank you very much!

採用された回答

per isakson
per isakson 2014 年 4 月 17 日
編集済み: per isakson 2014 年 4 月 18 日
Doesn't the info in Anonymous Functions cover your case?
I'm guessing. Try something like to create the anonymous function
Dt = ???;
s = ???;
f = ???;
fh = @(a,b,c,ii) Dt*f( t(ii+1),a,b,c) + s(ii)-[a,b,c];
(What are Dt, s, f and t ?) And call it
fh(a,b,c,ii)
.
Added later: With varying number of input variables
Try
[fh1,fh2] = cssm( );
a = 'a1';
b = 'b2';
c = 'c3';
fh1( a )
fh1( a, b, c )
fh2( a )
fh2( a,b,c )
which returns
a1
a1, b2, c3
a1
a1, b2, c3
where
function [fh1,fh2] = cssm( )
fh1 = @(varargin) foo( varargin{:} );
fh2 = @(varargin) disp( strjoin( varargin, ', ' ) );
function foo( varargin )
disp( strjoin( varargin, ', ' ) )
end
end

その他の回答 (1 件)

Piockñec
Piockñec 2014 年 4 月 18 日
Thank you for your answer! Your solution is right, when writing an anonymous function for 3 variables (a,b,c). The problem is that the number of variables can vary (a,b,c,d,e,f...)... because x is a symbolic array of unkwnowns.
However, I have written the programme so that I do not need to solve my issue. Thank you again!!!
  1 件のコメント
per isakson
per isakson 2014 年 4 月 18 日
I added a very simple case with a varying number of variables to my answer.

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

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by