Ron Bakker/MathLabHelp
Open MathLab ↗

Tutorial · Intermediate · 8 min

Working with data

Read tables from files and the web, explore the columns, fit a trend and save the result.

  1. Read a table from the web

    readtable turns a CSV file into a table whose columns you reach with a dot: T.Year. MathLab fetches web addresses written in the script before it runs. The site must allow access from browsers.

    T = readtable('https://raw.githubusercontent.com/datasets/co2-ppm/main/data/co2-annmean-mlo.csv')
    plot(T.Year, T.Mean, 'LineWidth', 2)
    xlabel('year'), ylabel('CO₂ (ppm)'), title('Mauna Loa')
    Try it ↗
  2. JSON from an API

    webread turns JSON into structs and cell arrays. The World Bank API returns {information, records}; each record is a struct.

    d = webread('https://api.worldbank.org/v2/country/NLD/indicator/SP.POP.TOTL?format=json&per_page=80');
    rows = d{2};
    yr = zeros(1, numel(rows)); pop = yr;
    for k = 1:numel(rows)
      yr(k) = str2double(rows{k}.date);
      if ~isempty(rows{k}.value), pop(k) = rows{k}.value / 1e6; else, pop(k) = NaN; end
    end
    plot(yr, pop, 'o-'), xlabel('year'), ylabel('millions'), title('Population of the Netherlands')
    Try it ↗
  3. Your own files

    Press Import (or drop a file on the editor) to add CSV, JSON, text or WAV files. They stay in your browser. The Files tab inserts the code to read them. This step makes a small file with writetable so you can try it.

    x = (1:10)';
    y = 3*x + 2 + randn(10, 1);
    writetable(struct('x', x, 'y', y), 'measurements.csv')
    disp('Download measurements.csv below the figure, then import it with the Import button')
    Try it ↗
    Download measurements.csv below the figure, then import it with the Import button
  4. Fit and summarise

    Once imported, the file reads like any other table. polyfit fits a line; height counts the rows.

    % (after importing measurements.csv)
    % T = readtable('measurements.csv');
    T = struct('x', (1:10)', 'y', 3*(1:10)' + 2 + randn(10, 1));
    p = polyfit(T.x, T.y, 1);
    plot(T.x, T.y, 'o', T.x, polyval(p, T.x), '-')
    title(sprintf('%d points: y = %.2f x + %.2f', height(T), p(1), p(2)))
    Try it ↗