cell indexing, extracting rectangular subset

4 vues (au cours des 30 derniers jours)
Knut Hvidsten
Knut Hvidsten le 19 Fév 2021
Commenté : dpb le 19 Fév 2021
I have been a MATLAB user for many years, and this is a question that has bugged me for a long time.
I am parsing a feed of text:
[tokens, matches] = regexp(result, template, 'tokens', 'match', 'dotexceptnewline');
Which produce a 700-element cell array, where each cell contains 4 subcells:
>>whos tokens
Name Size Bytes Class Attributes
tokens 1x700 392000 cell
>>tokens{1}
ans =
1×4 cell array
{'0'} {'00'} {'00.575807000'} {'some_string'}
Now I want to grab the 700 rows and 3 columns of numerical data and push them into a function that returns a numerical array. If tokens had been a regular array, I would have done:
tokens(:,1:3)
Of course, that does not work here. So what would you do except writing loops that seems totally un-MATLAB-esque?
I usually try stuff like:
tokens{:}(1:3)
{tokens{:}(1:3)}
tokens{:,1:3}
Then I give up, reminding myself that cells are unintuitive and find something else to attack.

Réponse acceptée

Stephen23
Stephen23 le 19 Fév 2021
Modifié(e) : Stephen23 le 19 Fév 2021
  1 commentaire
dpb
dpb le 19 Fév 2021
Yeah, and may be faster than cellfun...
>> str2double(vertcat(tokens{:}))
ans =
0 0 0.5758 NaN
0 0 0.5758 NaN
0 0 0.5758 NaN
0 0 0.5758 NaN
0 0 0.5758 NaN
>>
gets to the same place to just then pull off the first three columns. For some reason I can never remember vertcat when I want it... :(

Connectez-vous pour commenter.

Plus de réponses (1)

dpb
dpb le 19 Fév 2021
I just duplicated your example 5 times...
tokens=tokens.'; % reshape to column cell array
vals=cell2mat(cellfun(@str2double,tokens,'UniformOutput',false)); % convert to numeric
vals=ans(:,1:3); % return the known numeric columns only
The above returns
>> vals =
0 0 0.5758
0 0 0.5758
0 0 0.5758
0 0 0.5758
0 0 0.5758
>>
"Trick" is knowing that str2double returns NaN for non-convertible fields so first step results in an Nx4 double array with the last column being NaN.
Need to first organize by column vector, though, to get the output array in same shape as the input records.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by