Replacing character withing an cell using cellfun

12 ビュー (過去 30 日間)
Patrick
Patrick 2018 年 6 月 5 日
コメント済み: Walter Roberson 2018 年 6 月 11 日
I have a cell array called "ImpactTime" within a table called "hits" (see figure below). I'm attempting to change the 6th character in ImpactTime from a "." to a ":". I'm aware I can do this with a for loop
for i = 1:length(hits.ImpactTime);
hits.ImpactTime{i,1}(6)=':';
end
I was wondering if there was a way I could accomplish this using cellfun. I've tried a few methods but it won't allow me change a specific subset within each cell.
I have tried the following
hits.ImpactTime = cellfun(@(x) ':', hits.ImpactTime{:}(6))

採用された回答

Walter Roberson
Walter Roberson 2018 年 6 月 5 日
hits.ImpactTime = regexprep( hits.ImpactTime, '\.(\d\d\d)', ':\1');
Note that this assumes that there are always exactly three digits after the . that is to be replaced and assumes that pattern does not occur anywhere else in the input string.
  2 件のコメント
Patrick
Patrick 2018 年 6 月 11 日
Thanks this worked perfectly. I was a little surprised it wasn't possible with cellfun.
Walter Roberson
Walter Roberson 2018 年 6 月 11 日
hits.ImpactTime = cellfun(@(S) [S(1:end-4), ':', S(end-2:end)], hints.ImpactTime, 'uniform', 0);

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

その他の回答 (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