MATLAB Answers

How to replace a part of string in a cell array with a string that changes?

2 views (last 30 days)
Hello all,
I find it a little difficult to describe my problem accurately but basically, I have the following cell array:
{'0,31:1.04_MOTOR_SPEED_rpm' }
{'0,32:1.04_MOTOR_SPEED_rpm' }
{'0,33:1.04_MOTOR_SPEED_rpm' }
{'0,34:1.04_MOTOR_SPEED_rpm' }
{'0,31:1.08_MOTOR_TORQUE_pct' }
{'0,32:1.08_MOTOR_TORQUE_pct' }
{'0,33:1.08_MOTOR_TORQUE_pct' }
{'0,34:1.08_MOTOR_TORQUE_pct' }
{'0,31:25.04_TORQUE_REF_B_pct' }
{'0,32:25.04_TORQUE_REF_B_pct' }
{'0,33:25.04_TORQUE_REF_B_pct' }
{'0,34:25.04_TORQUE_REF_B_pct' }
And what I want to do is replace the numbers at the beginning of each cell ("0,31:1.03" and so on) so that in the end the cell array looks like this:
{'SD1_TORQUE_REF_3_%' }
{'SD2_TORQUE_REF_3_%' }
{'SD3_TORQUE_REF_3_%' }
{'SD4_TORQUE_REF_3_%' }
How can I do this kind of thing where I replace string with a string that changes in a systematic way, from SD1 to SD4? The number of rows isn't always the same but it is always a multiple of four so the first cell should always start with 'SD1_...' and the last cell with 'SD4_...'.
Edit: Forgot to mention, but I was considering doing this with a for- or while-loop, but apparently that's not recommended in Matlab? Why is that, and how should I then do it?
Edit 2: I should also mention that the numbers at the beginning of the cells are not always the same. However, they always looks more or less the same: #,##:##.##
I hope you understood what I'm going for, and thanks for any help in advance!

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 27 Jun 2019
>> D = regexprep(C,'^\d+,\d+(\d):\d+\.\d+','SD$1');
>> D{:}
ans = SD1_SPEED_MEASURED_1_rpm
ans = SD2_SPEED_MEASURED_1_rpm
ans = SD3_SPEED_MEASURED_1_rpm
ans = SD4_SPEED_MEASURED_1_rpm
ans = SD1_MOTOR_SPEED_rpm
ans = SD2_MOTOR_SPEED_rpm
ans = SD3_MOTOR_SPEED_rpm
ans = SD4_MOTOR_SPEED_rpm
ans = SD1_MOTOR_TORQUE_pct
ans = SD2_MOTOR_TORQUE_pct
ans = SD3_MOTOR_TORQUE_pct
ans = SD4_MOTOR_TORQUE_pct
ans = SD1_TORQUE_REF_B_pct
ans = SD2_TORQUE_REF_B_pct
ans = SD3_TORQUE_REF_B_pct
ans = SD4_TORQUE_REF_B_pct

More Answers (0)

Community Treasure Hunt

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

Start Hunting!