Is it possible for a formula to have a character array input?

1 次查看(过去 30 天)
Hi, I am trying to have the equation defining a function to vary depending on conditions. I want to know if its possible to add character arrays within the function definition.
Nc=3;
Np=2*Nc;
C=zeros(Np,1);
r=char('k(1)*C(1)*C(3)');
function dCdz = odes(z,C)
for i=1:2:Np
dCdz(i)= C(i+1);
dCdz(i+1)= Pe*(C(i+1)+r(1));
end
end
However, the function does not evaluate as I would expect. Is there a correct way to write this?
Thanks
  5 个评论
Amy Craig
Amy Craig 2018-2-26
I am unsure how to use this as the string does not constitute the entire function but only part of it.
Therefore I get the error:
Warning: The input to STR2FUNC "k(1)*t*C(1)*C(3)" is not a valid function name. This will generate an error in a future release.
Undefined operator '*' for input arguments of type 'function_handle'.
Stephen23
Stephen23 2018-2-26
编辑:Stephen23 2018-2-26
@Amy Craig: the str2func documentation at the link that I gave you explains that to define an anonymous function (i.e. not one saved as an Mfile) you will need to prefix the string with @(...), defining any variables you need to call that function with. Note that the documentation also states " Workspace variables are not available to the str2func function. Therefore, include values in the character vector that are necessary to evaluate the expression and that are not defined as function inputs".
So you would need something like this:
fun = str2func('@(k,t,C)k(1)*t*C(1)*C(3)')
and call it with the appropriate input arguments:
fun(k,t,C)

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2018-2-26
编辑:Jan 2018-2-26
A formula can have a char vector as input, but it is evaluated as char vector. For
r = char('k(1)*C(1)*C(3)');
the values of r(1) is 'k'. This is converted to its ASCII value, such that the double 107 is used. This is most likely not, what you want. But what do you want exactly? What is "k" and what do you expect as result of "r(1)"?
Maybe you want an anonymous function:
r = @(k, C) k(1)*C(1)*C(3);
% Needs to be a nested function:
function dCdz = odes(z,C)
dCdz = zeros(1, Np); % Pre-allocate!
for i=1:2:Np
dCdz(i) = C(i+1);
dCdz(i+1)= Pe*(C(i+1) + r(1, C));
end
end

类别

Help CenterFile Exchange 中查找有关 Functions 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by