How to properly apply cellfun in this case - text spliting
2 views (last 30 days)
Show older comments
Pawel Jastrzebski
on 5 Sep 2018
Answered: Pawel Jastrzebski
on 6 Sep 2018
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?
0 Comments
Accepted Answer
Stephen23
on 5 Sep 2018
Edited: Stephen23
on 5 Sep 2018
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
0 Comments
More Answers (2)
Rik
on 5 Sep 2018
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)
0 Comments
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!