Replace letters in matrix
1 回表示 (過去 30 日間)
古いコメントを表示
Ymkje Lize Neuteboom
2019 年 11 月 12 日
コメント済み: Walter Roberson
2019 年 11 月 12 日
I need to replace compass abbreviations with their corresponding direction in degrees. I've done the following, and it works. However, this seems like an unnecessary long piece of code. Is there a way to do this more concise?
for i = 1:size(Wave_direction,1)
Wave_direction(i,2)=replace(Wave_direction(i,2), 'NNE', '22.5');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'ENE', '67.5');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'ESE', '112,5');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'SSE', '157.5');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'SSW', '202.5');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'WSW', '247.5');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'WNW', '292.5');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'NNW', '337.5');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'NE', '45');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'SE', '135');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'SW', '225');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'NW', '315');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'N', '360');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'E', '90');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'S', '180');
Wave_direction(i,2)=replace(Wave_direction(i,2), 'W', '270');
end
2 件のコメント
Walter Roberson
2019 年 11 月 12 日
regexprep(Wave_direction(i,2), {'NNE', 'ENE', 'ESE'}, {'22.5', '67.5', '112.5'})
You should list the longer patterns first, like you do already.
採用された回答
Guillaume
2019 年 11 月 12 日
I would be wary of using regexprep as per Walter's code for that. It relies on the fact that replacements are attempted in the order they occur in the cell array. While this is most likely the case, the documentation does not specify it so you're relying on undefined behaviour. At some point this may change and the code will return incorrect results.
Guaranteed to work and just as simple:
patterns = {'NNE', 'ENE', 'ESE', 'SSE', ..etc}; %order does not matter
replacements = {'22.5', '67.5', '112.5', '157.5', ..etc}; %order has to match patterns obviously
[found, whichrep] = ismember(Wave_direction(:, 2), patterns);
Wave_direction(found, 2) = replacements(whichrep(found));
1 件のコメント
Walter Roberson
2019 年 11 月 12 日
It is documented, so it can be counted on.
When expression is a cell array or a string array, regexprep applies the first expression to str, and then applies each subsequent expression to the preceding result.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!