How to apply a matrix to a function?
2 ビュー (過去 30 日間)
古いコメントを表示
Hello all,
I already uploaded a similar question, but I had not got any answer, so I would like to ask again. I am tyring to apply a matrix to a function, however it gives an error. Following is an example that I am trying to do. Due to convenience, I just use 5 variables in this example.
syms 'T' [1 5]
f = sym(zeros(5, 5));
f(:,:) = T1 + T2 + T3 + T4 + T5;
x_vars = 1:5;
f_ftn (T1, T2, T3, T4, T5) = f;
values = f_ftn(x_vars);
If I run this code, I got an error "Symbolic function expected 5 input arguments but received 1."
I guess Matlab consider x_vars as one input, though it has 5 values in it. Is there any way I can apply the x_vars to f_ftn?
Thank you in advance!
0 件のコメント
採用された回答
Walter Roberson
2021 年 1 月 14 日
編集済み: Walter Roberson
2021 年 1 月 14 日
No, there is no way to do that.
When you create a symbolic function by assignment to a variable indexed with a list of symbols, MATLAB will take the list of symbols and horzcat it. The horzcat step will get an error if the number of rows in the entries is not all the same. Then MATLAB will check to see if the result has exactly one row and will error if not. It will check that all the entries are simple symbolic variables.
Note that because of this behavior,
g(T) = something
g(T1, T2, T3, T4, T5) = something
g([T1, T2], T3, [T4, T5]) = something
will mean the same thing: the list of variables will be collapsed into a single list internally. The structure you give in the assignment such as T or listing them out individually, has no effect on the outcome.
Once the list of variables has been created, it is used in symfun() to construct the function, and each different variable is expanded to a different parameter for the resulting function.
Once the function is constructed, at function call time, subsref is invoked and the internal code subs() in the parameters passed for the variables, using subs(expression, {variable list},{value list}) syntax. No attempt is made to match number of passed parameters to number of defined parameters to see if you want one to one correspondence .
If you want to have a list of values expand into a vector of values, you can define an adapter function, or you can
EXPAND = @(C)C{:}
g(EXPAND(num2cell(list_of_values))
3 件のコメント
Walter Roberson
2021 年 1 月 14 日
syms 'T' [1 5]
f = sym(zeros(5, 5));
f(:,:) = T1 + T2 + T3 + T4 + T5;
x_vars = 1:5;
g (T1, T2, T3, T4, T5) = f;
x_cell = num2cell(x_vars);
g(x_cell{:})
I forgot that a literal {} expansion is treated differently than code that calculates the same thing.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Symbolic Math Toolbox についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!