Replace letters in matrix

1 次查看(过去 30 天)
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
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.
Ymkje Lize Neuteboom
Thanks! Works like a charm =)

请先登录,再进行评论。

采纳的回答

Guillaume
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
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 CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by