cell indexing, extracting rectangular subset

조회 수: 3 (최근 30일)
Knut Hvidsten
Knut Hvidsten 2021년 2월 19일
댓글: dpb 2021년 2월 19일
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.

채택된 답변

Stephen23
Stephen23 2021년 2월 19일
편집: Stephen23 2021년 2월 19일
  댓글 수: 1
dpb
dpb 2021년 2월 19일
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... :(

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

dpb
dpb 2021년 2월 19일
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.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by