Problem with str2func and error with valid function name
古いコメントを表示
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
採用された回答
その他の回答 (4 件)
Walter Roberson
2012 年 2 月 11 日
0 投票
If your government has not asked the Canadian Embassy to contact me, then this isn't an emergency.
A R
2012 年 2 月 11 日
0 投票
2 件のコメント
A R
2012 年 2 月 11 日
Walter Roberson
2012 年 2 月 11 日
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));
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!