Is it possible for a formula to have a character array input?
1 view (last 30 days)
Show older comments
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 Comments
Stephen23
on 26 Feb 2018
Edited: Stephen23
on 26 Feb 2018
@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)
Answers (1)
Jan
on 26 Feb 2018
Edited: Jan
on 26 Feb 2018
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
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!