Editing a cell array.

6 views (last 30 days)
Gagan Bansal
Gagan Bansal on 30 Jan 2019
Edited: Stephen23 on 30 Jan 2019
I have a cell array
1ms 1kA 10V
2ms 2.2kA 3V
3ms 3.6kA 5.4V
I want to remove 'ms', 'kA' & 'V' from the cell array and then convert it into a matlab matrix with numerical value for further calculations.

Answers (2)

madhan ravi
madhan ravi on 30 Jan 2019
Edited: madhan ravi on 30 Jan 2019
C={'1ms' '1kA' '10V'
'2ms' '2.2kA' '3V'
'3ms' '3.6kA' '5.4V'};
Matrix=str2double(cellfun(@(x)regexp(x,'^(\d{0,5}\.{0,1}\d{0,5})','match'),C))
  2 Comments
Stephen23
Stephen23 on 30 Jan 2019
Edited: Stephen23 on 30 Jan 2019
Note that regexp accepts a cell array of character vectors, so the cellfun call is totally superfluous. I recommend using the option 'once' to simplify the output handling.
Some notes about the regular expression itself:
\d{0,5}
why limited to just five digits?
\.{0,1}
is simpler as
\.?
The grouping parentheses are not required.
madhan ravi
madhan ravi on 30 Jan 2019
Edited: madhan ravi on 30 Jan 2019
Agree with Stephen:
Matrix=cellfun(@str2double,regexp(C,'^(\d*\.?\d*)','match'))
% or
Matrix=str2double(regexp(C,'^(\d*\.?\d*)','match','once'))
Gives:
Matrix =
1.0000 1.0000 10.0000
2.0000 2.2000 3.0000
3.0000 3.6000 5.4000

Sign in to comment.


Stephen23
Stephen23 on 30 Jan 2019
Edited: Stephen23 on 30 Jan 2019
To get the actual numeric values taking into account the SI prefixes you can use my FEX submission sip2num, which can be downloaded from FEX:
>> C = {'1ms','1kA','10V';'2ms','2.2kA','3V';'3ms','3.6kA','5.4V'}
C =
'1ms' '1kA' '10V'
'2ms' '2.2kA' '3V'
'3ms' '3.6kA' '5.4V'
>> N = cellfun(@sip2num,C)
N =
0.001 1000 10
0.002 2200 3
0.003 3600 5.4

Categories

Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!