convert string to double

7 ビュー (過去 30 日間)
Christelle Requena
Christelle Requena 2017 年 12 月 12 日
回答済み: Walter Roberson 2017 年 12 月 12 日
If I have a string like : `A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)`
How I can convert it to double ?
I tried
B = str2num(A) % I obtain an empty matrix
or
B = str2double(A) % I obtain a Nan response...
How can I fixe it ?
  1 件のコメント
Jos (10584)
Jos (10584) 2017 年 12 月 12 日
What do you expect to get? Do you want to evaluate the formula?

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2017 年 12 月 12 日
MATLAB 5.1 and later, no special toolboxes:
S = 'A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)';
temp = vectorize(regexp(S, '(?<==\s*)\S.*', 'match', 'once'));
vars = symvar(temp);
F = str2func(['@(', strjoin(vars,','), ') ', temp ]);
Now execute the function handle F, passing in the variables named in vars, in order, which in this case would be f1, f2, t.
But I suspect this is not the answer you are looking for. An answer closer to what you are looking for would be:
R2017b and later with Symbolic Toolbox
S = 'A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)';
temp = regexp(S, '(?<==\s*)\S.*', 'match', 'once');
tempsym = str2sym(temp);
A = double( subs(tempsym) );
R2017a and earlier with Symbolic Toolbox
S = 'A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)';
temp = regexp(S, '(?<==\s*)\S.*', 'match', 'once');
tempsym = sym(temp); %will probably give a warning message
A = double( subs(tempsym) );
But I suspect those are not the answers you are looking for either.
The answer I suspect you are looking for is:
S = 'A = cos(2*pi*f1*t) + 4*sin(2*pi*f2*t)';
eval(S);
%the result will be in A
We recommend against using eval() !!

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by