How to properly apply cellfun in this case - text spliting

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

Stephen23
Stephen23 il 5 Set 2018
Modificato: Stephen23 il 5 Set 2018
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

Più risposte (2)

Rik
Rik il 5 Set 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)

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

Categorie

Scopri di più su Startup and Shutdown in Help Center e File Exchange

Prodotti


Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by