You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用textscan将字符串转为表格?Matlab处理COVID-19 CSV数据问询

Efficiently Convert JHU COVID-19 CSV Data from URL to MATLAB Table

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:

  1. Fetch the raw data string

    rawData = urlread('your_JHU_covid_csv_url'); % Replace with the actual JHU data URL
    
  2. Parse 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 %q instead of %s is crucial here—JHU’s data sometimes includes region names with commas (like "King County, WA") wrapped in quotes, and %q correctly reads these as single strings.

  3. 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—webread is the recommended replacement for fetching web data.
  • For very large CSV files, readtable is also more efficient at memory management than manual textscan parsing.

内容的提问来源于stack exchange,提问作者Christian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:32:50