How to Convert a column with Char in Cell matrice to Number?

4 ビュー (過去 30 日間)
Vyshakh Pv
Vyshakh Pv 2019 年 4 月 16 日
コメント済み: Vyshakh Pv 2019 年 5 月 5 日
  • I have a cell array:
A =
'Time' 'Name' 'Location' 'Duration' 'Remarks'
'100' 'John' 'Abc' '1000' 'Nill'
'101' 'Tim' 'Def' '1000' 'Nill'
'102' 'Tom' 'Ghi' '2000' 'Nill'
'103' 'Jim' 'Jkl' '4500' 'Nill'
Here I want to convert A(2:4, 1), and A(2:4, 4) to numbers and save to same matrice A.
I can do this using a LOOP and STR2DOUBLE(), but it is very time consuming when the matrice is very large.
Is there any method to convert a range of char-values in a cell matrice to to numbers?
I am looking for someting like:
A(2:4, 1) = str2double( A(2:4, 1) ) %This command is not working
A(2:4, 4) = str2double( A(2:4, 4) ) %This command is not working
  • Output should look like:
A =
'Time' 'Name' 'Location' 'Duration' 'Remarks'
100 'John' 'Abc' 1000 'Nill'
101 'Tim' 'Def' 1000 'Nill'
102 'Tom' 'Ghi' 2000 'Nill'
103 'Jim' 'Jkl' 4500 'Nill'

採用された回答

Stephen23
Stephen23 2019 年 4 月 16 日
編集済み: Stephen23 2019 年 4 月 16 日
You almost got it right, you just need to split the numeric array into a cell array so that it can be allocated back to the cell array A:
A(2:4,1) = num2cell(str2double(A(2:4,1)))
A(2:4,4) = num2cell(str2double(A(2:4,4)))
Or simply on one line:
A(2:4,[1,4]) = num2cell(str2double(A(2:4,[1,4])))
  1 件のコメント
Vyshakh Pv
Vyshakh Pv 2019 年 5 月 5 日
actually.....
for i = first : last
mat{i, col} = str2double(mat{i, col});
end
is faster than ....
mat(first:end, col) = num2cell(str2double(mat(first:end, col)));

サインインしてコメントする。

その他の回答 (1 件)

KSSV
KSSV 2019 年 4 月 16 日
編集済み: KSSV 2019 年 4 月 16 日
A = {'Time' 'Name' 'Location' 'Duration' 'Remarks'
'100' 'John' 'Abc' '1000' 'Nill'
'101' 'Tim' 'Def' '1000' 'Nill'
'102' 'Tom' 'Ghi' '2000' 'Nill'
'103' 'Jim' 'Jkl' '4500' 'Nill'} ;
T = cell2table(A(2:end,:),'VariableNames',A(1,:)) ;
T.(1) = cell2mat(T.(1)) ;
T.(4) = cell2mat(T.(4)) ;
T

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by