Azzera filtri
Azzera filtri

Editing a cell array.

3 visualizzazioni (ultimi 30 giorni)
Gagan Bansal
Gagan Bansal il 30 Gen 2019
Modificato: Stephen23 il 30 Gen 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.

Risposte (2)

madhan ravi
madhan ravi il 30 Gen 2019
Modificato: madhan ravi il 30 Gen 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 Commenti
Stephen23
Stephen23 il 30 Gen 2019
Modificato: Stephen23 il 30 Gen 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 il 30 Gen 2019
Modificato: madhan ravi il 30 Gen 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

Accedi per commentare.


Stephen23
Stephen23 il 30 Gen 2019
Modificato: Stephen23 il 30 Gen 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

Categorie

Scopri di più su Cell Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by