Problem with str2func and error with valid function name
Afficher commentaires plus anciens
I have to concatenate a defined number of strings into one, then to convert this string into a function that I memorize. Then I have to give input to this new function to calculate many values.
As you'll see below I use str2func to do that. When I test this function, Matlab warns me that my function is unvalid, so my program doesn't work right at its beginning, however after many tries I don't know which other way to use.
Here is the code
function [value]=squareAndSum(stringFunc,x,y)
%x and y are two vectors, stringFunc the string we want to convert %into a function
%this function must calculate the value of this new fonction for %each y and use it to update value
value=0;
totalDots=length(y);
fh=str2func(stringFunc);
yApprox=zeros(totalDots);
for i=1:1:totalDots
yApprox(i)=fh(x(i));
squared=(y(i)-yApprox(i))*(y(i)-yApprox(i));
value=value+squared;
end;
When I test it with x=[1 ; 2 ; 3 ; 4], y=[5 ; 6 ; 7 ; 8] and stringFunc = '2*cos', Matlab displays :
Warning: The input to STR2FUNC "2*cos" is not a valid function name. This will generate an error in a future release.
> In squareAndSum at 6
??? Undefined function or method '2*cos' for input arguments of type 'double'.
Error in ==> squareAndSum at 9
yApprox(i)=fh(x(i));
With stringFunc = 'cos' however it works, of course, but I really need to concatenate different strings to create a new function for my work. (and I have very little time...)
Sorry if the question seems rather simple, I am quite new with Matlab.
Thanks in advance for your help
Réponse acceptée
Plus de réponses (4)
Walter Roberson
le 11 Fév 2012
0 votes
If your government has not asked the Canadian Embassy to contact me, then this isn't an emergency.
1 commentaire
A R
le 11 Fév 2012
A R
le 11 Fév 2012
A R
le 11 Fév 2012
0 votes
2 commentaires
A R
le 11 Fév 2012
Walter Roberson
le 11 Fév 2012
If you only have one x and it is at the end, then
fh = str2func(['@(x) ' stringFunc '(x)']);
You would not use @()
You do not need to assign x(i) to a variable:
yApprox(i)=fh(x(i));
A R
le 11 Fév 2012
Catégories
En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!