Convert large cell array to double
显示 更早的评论
Hi, I have problem with conversation cell array to double. I have this format:
'gfc' '0' '0' '0.100000000000e+01' '0.000000000000e+00'
'gfc' '1' '0' '0.000000000000e+00' '0.000000000000e+00'
'gfc' '1' '1' '0.000000000000e+00' '0.000000000000e+00'
'gfc' '2' '0' '-.484165343771e-03' '0.000000000000e+00'
'gfc' '2' '1' '-.316745955888e-09' '0.141736103677e-08'
'gfc' '2' '2' '0.243935242430e-05' '-.140031280033e-05'
and I use this code:
for i = 1:4
model(:, i) = sscanf(sprintf('%s\v',model_c{:,i+1}),'%f\v');
end
When I convert a small model which it has degree and order 100 (about 5 500 lines), my code works. But when I want convert large model with degree and order for example 2200 (about 2 500 000 lines), code crashed on the third column. And Matlab writes 'Subscripted assignment dimension mismatch'. Can someone help me?
采纳的回答
更多回答(1 个)
Yes that seems overly complicated. Wouldn't
model = str2double(model_c(:, 2:5));
%or
model = cellfun(@(c) sscanf('%f', c), model_c(: 2:5));
be faster and certainly simpler.
Even better would be to fix whatever is generating the cell array so that it creates a numeric matrix in the first place. If you're importing that from a text file, fixing the import would be better.
3 个评论
Richard Kratochvíl
2018-3-13
编辑:Richard Kratochvíl
2018-3-14
"Wouldn't ... be faster and certainly simpler."
Not faster. Actually this code:
sscanf(sprintf('%s\v',model_c{:,i+1}),'%f\v');
is likely the fastest way to convert multiple cells of char vectors to numeric. str2double, and any other inbuilt functions will be slower than this. See:
I did a lot of experimentation on this for my FEX submission natsort, and the results were quite clear that sprintf and sscanf is hard to beat.
Algorithmically, it makes no sense to first concatenate all the strings to then parse them instead of just parsing them. The concatenation is an unneeded step.
Since str2double is slower it clearly is not implemented efficiently. What you need is a sscanf that supports cell arrays. Then the concatenation would not be necessary.
Thankfully, I don't usually have to deal with this as all the import I do is binary. Much more efficient!
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!