Combine Strrep in one Line.

3 ビュー (過去 30 日間)
FishermanJack
FishermanJack 2017 年 11 月 30 日
コメント済み: FishermanJack 2017 年 12 月 4 日
Hi, is there any way that i Combine strrep as one line in my Code for different values. for example.
a = strrep(a, 'x','y'); a = strrep(a, 'z','w');

採用された回答

KL
KL 2017 年 11 月 30 日
use replace with cell arrays,
a = 'abcxyz'
old = {'x';'z'};
new = {'y';'w'};
a = replace(a, old,new)
  3 件のコメント
KL
KL 2017 年 11 月 30 日
sorry, that does not work for me
What does it mean? Do you get an error message?
My guess would be that you're using a matlab version older than 2016b. Anywayt try regexprep,
a = regexprep(a, old,new);
FishermanJack
FishermanJack 2017 年 11 月 30 日
編集済み: FishermanJack 2017 年 11 月 30 日
yes, thanks,regexprep does the Job very well. :D

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

その他の回答 (1 件)

Jan
Jan 2017 年 11 月 30 日
編集済み: Jan 2017 年 11 月 30 日
has = 'xy';
rep = 'zw';
[Lia, Locb] = ismember(a, has);
a(Lia) = rep(Locb);
[EDITED] I assume strrep has less overhead. For many changes, a lookup table will be more efficient:
function s = StrRepList(s, old, new)
if numel(old) < 20 % GUESSED limit!
for k = 1:numel(old)
s = strrep(s, old(k), new(k));
end
else
lut = char(0):char(255);
lut(old + 1) = new;
s = lut(s + 1);
end
end
Some tests with tic/toc will help to find a suitable limit to decide for a strrep loop or a lookup table method. Maybe it depends on the size of s also.
  2 件のコメント
FishermanJack
FishermanJack 2017 年 11 月 30 日
i will try this because regexprep is much slower than strrep..
FishermanJack
FishermanJack 2017 年 12 月 4 日
i implented this in my Code, but as i see with tic/toc the most efficient way is with strrep. thank you anyway

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by