How to properly apply cellfun in this case - text spliting

1 回表示 (過去 30 日間)
Pawel Jastrzebski
Pawel Jastrzebski 2018 年 9 月 5 日
回答済み: Pawel Jastrzebski 2018 年 9 月 6 日
I've got a table like this and my task is to separate the parameter name from a value:
t =
10×1 table
Var1
________________
'Pa 0.749µm'
'Pq 0.800µm'
'Pz 1.458µm'
'Pp 0.748µm'
'Pv 0.710µm'
'Pt 4.914µm'
'Psk -0.321'
'Pkµ 1.726'
'Pc E_0010'
'PSm E_0010'
So first I came up with the code to identify all of the spaces in the cells and then fins the first and last blank in each row:
separator = ' ';
BlanksIdx = strfind(t{:,1},separator); % Indexes of all blanks in the rows
Blank1st = cellfun(@min, BlanksIdx);
BlankLast = cellfun(@max, BlanksIdx);
With the output for Blank1st being:
Blank1st =
3
3
3
3
3
3
4
4
3
4
At this point I wanted to use cellfun() again to carry out a separation:
A = cellfun(@(x) x(1:Blank1st-1),t{:,1},'UniformOutput',false)
However, this always truncates the text after 2nd character:
A =
10×1 cell array
{'Pa'}
{'Pq'}
{'Pz'}
{'Pp'}
{'Pv'}
{'Pt'}
{'Ps'}
{'Pk'}
{'Pc'}
{'PS'}
How do I make this code to work so it separates the name of the parameter correctly?

採用された回答

Stephen23
Stephen23 2018 年 9 月 5 日
編集済み: Stephen23 2018 年 9 月 5 日
It is simpler and more efficient to use a regular expression:
C = regexp(t.Var1,'\S+','match');
C = vertcat(C{:})
Giving the two columns in one cell array:
>> C{:,1}
ans = Pa
ans = Pq
ans = Pz
ans = Pp
ans = Pv
ans = Pt
ans = Psk
ans = Pkµ
ans = Pc
ans = PSm
>> C{:,2}
ans = 0.749µm
ans = 0.800µm
ans = 1.458µm
ans = 0.748µm
ans = 0.710µm
ans = 4.914µm
ans = -0.321
ans = 1.726
ans = E_0010
ans = E_0010

その他の回答 (2 件)

Rik
Rik 2018 年 9 月 5 日
You need to have the index available as a separate input:
A = cellfun(@(x,ind) x(1:ind-1),t{:,1},num2cell(Blank1st),'UniformOutput',false)

Pawel Jastrzebski
Pawel Jastrzebski 2018 年 9 月 6 日
Rik Wisselink, Stephen Cobeldick many thanks to you both for the suggestions. I'll go forward with the regexp solution as it seems cleaner.

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by