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!

采纳的回答

Walter Roberson
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
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{:})
ans = 
I forgot that a literal {} expansion is treated differently than code that calculates the same thing.
Johnny Yoon
Johnny Yoon 2021-1-15
That works nicely! Thank you very much!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by