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
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 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!