Tutorial · Intermediate · 8 min
Working with data
Read tables from files and the web, explore the columns, fit a trend and save the result.
Read a table from the web
readtableturns 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.
Try it ↗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')JSON from an API
webreadturns JSON into structs and cell arrays. The World Bank API returns{information, records}; each record is a struct.
Try it ↗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')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
writetableso you can try it.
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')Download measurements.csv below the figure, then import it with the Import button
Fit and summarise
Once imported, the file reads like any other table.
polyfitfits a line;heightcounts the rows.
Try it ↗% (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)))