cell indexing, extracting rectangular subset
4 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Stephen23
2021-2-19
编辑:Stephen23
2021-2-19
The simplest (and usually quite efficient) approach is to use a comma-separated list to create one cell array:
tmp = vertcat(tokens{:}); % -> 700x4 cell array
mat = str2double(tmp(:,1:3)) % -> 700x3 double
Most of your syntax attempts do not work for the reason give here:
1 个评论
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
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!