MATLAB Answers

0

Replace letters in matrix

Asked by Ymkje Lize Neuteboom on 12 Nov 2019
Latest activity Commented on by Walter Roberson
on 12 Nov 2019
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 Comments

Walter Roberson
on 12 Nov 2019
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.
Thanks! Works like a charm =)

Sign in to comment.

Products


Release

R2019a

1 Answer

Guillaume
Answer by Guillaume
on 12 Nov 2019
 Accepted Answer

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 Comment

Walter Roberson
on 12 Nov 2019
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.

Sign in to comment.