Operate a string in a cell matrix

5 ビュー (過去 30 日間)
Kyle
Kyle 2012 年 9 月 28 日
Hi, I have a cell matrix imported from excel:
[39] [1232] [ 567] [ NaN]
[40] [ 48] [ 41] [ 949]
[41] [ 48] [ 1686] [ 40]
[42] [ 754] [ 753] [ 40]
[43] [ 48] '800 1069 1152' [ 983]
[44] [ 43] [ 48] '700 109 152'
[45] [ 52] [ 1340] [ 1363]
[46] [1340] [ 45] [ 1594]
there are all number with each taking one gird in excel except two "800 1069 1152" and '700 109 152' taking a single grid. In matlab, by [num,txt,raw] = xlsread() the raw matrix is a cell matrix with '800 1069 1152' a string. Is there a way I want to just keep 800, and 700 from those two strings, and convert this cell matrix to a normal matrix for future programming?
Thank you for any suggestion Kyle

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 28 日
編集済み: Azzi Abdelmalek 2012 年 9 月 28 日
A={[39] [1232] [ 567] [ NaN]
[40] [ 48] [ 41] [ 949]
[41] [ 48] [ 1686] [ 40]
[42] [ 754] [ 753] [ 40]
[43] [ 48] '800 1069 1152' [ 983]
[44] [ 43] [ 48] '700 109 152'
[45] [ 52] [ 1340] [ 1363]
[46] [1340] [ 45] [ 1594]}
r=cellfun(@(x) isstr(x),A)
q=cellfun(@(x) regexp(x,' ','split'),A(r),'uni',false)
A(find(r==1))=num2cell(cellfun(@(x) str2num(x{1}),q))
out=cell2mat(A)
  2 件のコメント
Kyle
Kyle 2012 年 9 月 28 日
thank you Azzi
Jan
Jan 2012 年 9 月 28 日
Some simplifications:
r = cellfun('isclass', A, 'char');
A(r) = cellfun(@(x) sscanf(x, '%g', 1), A(r), 'uni', false);
out = cell2mat(A);

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

その他の回答 (1 件)

Muthu Annamalai
Muthu Annamalai 2012 年 9 月 28 日
Hello Kyle,
Solution is fairly straightforward.
First you can identify the locations where '*xlsread*' bailed out, by looking for the NaN in the matrix p,
[p,q,r]=xlsread('xl_file_name.xls')
[R,C]=find(isnan(p))
and then work to extract the first element, which is what you mention in the post, from 'cell-string' of numbers to a 'double' type. You can do this by, working your way through the row-column index
for idx = 1:length(R)
long_str = r{R(idx),C(idx)};% pickup the long string
t=regexp(long_str,' ','split'); %split it into n-element strings
r{R(idx),C(idx)}=str2double(t{1});% convert to double
end
Finally the magic step is to convert your cell-matrix into a regular matrix,
p = cell2mat(r);
Together your code should look like,
[p,q,r]=xlsread('xl_file.xls')
[R,C]=find(isnan(p))
for idx = 1:length(R)
long_str = r{R(idx),C(idx)};% pickup the long string
t=regexp(long_str,' ','split'); %split it into n-element strings
r{R(idx),C(idx)}=str2double(t{1});% convert to double
end
p = cell2mat(r)
HTH, -Muthu
  1 件のコメント
Kyle
Kyle 2012 年 9 月 28 日
Thank you Muthu

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by