フィルターのクリア

How to recognize multiplication with out *

1 回表示 (過去 30 日間)
Dr. ARK
Dr. ARK 2015 年 3 月 19 日
編集済み: Dr. ARK 2015 年 3 月 20 日
Hello!!
I want to write a code where you can input a string of a polynomial for instance '2x+3' and matlab returns the string as '2*x+3'. The user can input any string of a polynomial and matlab adds the * where needed.
I was thinking of possibly using a for loop (length of the string) where it passes through each indices and use isletter or isnumeric and if I get a numeric followed by a letter The code addes a * in between.
Can someone help me implement this or have a better way of doing so. Thanks a lot!
  3 件のコメント
John D'Errico
John D'Errico 2015 年 3 月 19 日
And of course, how would it deal with the number 3e2, as this is a perfectly legal way of writing the number 300.
Dr. ARK
Dr. ARK 2015 年 3 月 19 日
True, thanks for those questions!!

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

採用された回答

James Tursa
James Tursa 2015 年 3 月 19 日
編集済み: James Tursa 2015 年 3 月 19 日
Brute force loop:
s = '2x + 3 - 5y';
isdigit = @(x)(x>='0'&x<='9');
s(s==' ') = []; % if you want to protect against blanks
n = numel(s);
t = s(1);
for k=2:n
if( isdigit(s(k-1)) && isletter(s(k)) )
t = [t '*'];
end
t = [t s(k)];
end
t =
2*x+3-5*y
There are ways to vectorize this and not increase the size of t in a loop, but for the small string size you will likely be dealing with it is hardly worth the effort.

その他の回答 (1 件)

Guillaume
Guillaume 2015 年 3 月 19 日
編集済み: Guillaume 2015 年 3 月 19 日
Assuming you just want to insert a '*' between any number followed by any letter (that is ignore problems like brackets and 3e2 notation):
expression = '2x + 3 - 5y';
newexpression = regexprep(expression, '([0-9])([a-zA-Z])', '$1*$2')
edit: Actually, the following will not insert a '*' when the letter is followed by another number so will cope with 'e' notation:
expression = '2x + 3e5 - 1e2y';
newexpression = regexprep(expression, '([0-9])([a-zA-Z])(?![0-9])', '$1*$2')

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by