如何使用textscan将字符串转为表格?Matlab处理COVID-19 CSV数据问询
Hey there! You’re right—saving the data to a local file is totally unnecessary. Let’s walk through two clean solutions to turn that urlread output directly into a MATLAB table, no intermediate files required.
Option 1: Use textscan with Your Existing urlread Workflow
First, let’s handle the raw string from urlread properly, especially since your CSV has string-based region columns followed by numeric date columns. Here’s step-by-step code:
Fetch the raw data string
rawData = urlread('your_JHU_covid_csv_url'); % Replace with the actual JHU data URLParse the header to build a dynamic format spec
We need to account for the first two string columns and the rest numeric columns. First split the header line to count columns:lines = strsplit(rawData, '\n'); header = strsplit(lines{1}, ','); % Build format spec: 2 string columns (%q handles quoted strings with commas) + rest numeric formatSpec = ['%q', '%q', repmat('%f', 1, length(header)-2)];Using
%qinstead of%sis crucial here—JHU’s data sometimes includes region names with commas (like "King County, WA") wrapped in quotes, and%qcorrectly reads these as single strings.Scan the string and convert to a table
% Skip the header line, use comma delimiter dataCells = textscan(rawData, formatSpec, 'Delimiter', ',', 'HeaderLines', 1, 'ReturnOnError', false); % Convert cell array to table with original column names covidTable = cell2table(dataCells, 'VariableNames', header);
Option 2: The Simplest Solution (MATLAB R2019b+)
If you’re using a newer MATLAB version, you can skip urlread entirely—readtable supports direct URL reading! This is way more concise:
covidTable = readtable('your_JHU_covid_csv_url');
readtable automatically detects column types (strings for regions, numbers for case counts) and handles quoted strings out of the box. It’s the most straightforward approach if your MATLAB version allows it.
Quick Notes
- If you get errors with
urlread, note that it’s been deprecated in newer MATLAB releases—webreadis the recommended replacement for fetching web data. - For very large CSV files,
readtableis also more efficient at memory management than manualtextscanparsing.
内容的提问来源于stack exchange,提问作者Christian

