Editing a cell array.

4 次查看(过去 30 天)
Gagan Bansal
Gagan Bansal 2019-1-30
编辑: Stephen23 2019-1-30
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.

回答(2 个)

madhan ravi
madhan ravi 2019-1-30
编辑:madhan ravi 2019-1-30
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 个评论
Stephen23
Stephen23 2019-1-30
编辑:Stephen23 2019-1-30
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 2019-1-30
编辑:madhan ravi 2019-1-30
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

请先登录,再进行评论。


Stephen23
Stephen23 2019-1-30
编辑:Stephen23 2019-1-30
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

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by