MATLAB is widely used for numerical analysis, data science, engineering, research, and visualization. Weather data can be a valuable input to many of these analyses, from studying environmental trends to comparing weather conditions with operational or business data.
In this tutorial, we’ll use the Visual Crossing Weather API to retrieve historical and forecast weather data directly into MATLAB.
MATLAB’s built-in webread() function can make the HTTP request and automatically convert the returned JSON weather data into MATLAB structures, so no additional JSON library is required.
If you want to explore or download weather datasets before writing MATLAB code, you can also use Visual Crossing Weather Data.
What we’ll do
In this tutorial, we’ll:
- Create a Timeline Weather API request.
- Retrieve weather data using MATLAB’s
webread()function. - Access daily weather values from the returned structure.
- Plot maximum and minimum temperatures.
- Retrieve historical weather for a date range.
- Add additional weather elements to your analysis.
- Handle Weather API errors in MATLAB.
Get your Visual Crossing Weather API key
You’ll need a Visual Crossing Weather account and API key before making API requests.
If you’re new to the Weather API, see Getting Started with the Weather API.
Your API key authenticates requests made to the Weather API.
In the examples below, we’ll read the key from an environment variable rather than placing it directly in the MATLAB source code.
Set an environment variable named:
VISUAL_CROSSING_API_KEY
MATLAB can then retrieve it using:
apiKey = getenv("VISUAL_CROSSING_API_KEY");
if strlength(apiKey) == 0
error("VISUAL_CROSSING_API_KEY is not set.");
end
This helps keep your API key out of source files that may be shared or committed to a source-code repository.
Visual Crossing plans include usage and request limits, so applications should be designed to operate within the limits of the account plan being used.
Understanding the Timeline Weather API request
The Visual Crossing Timeline Weather API uses the following basic URL structure:
/timeline/[location]/[date1]/[date2]
Only the location is required.
For example, a forecast request for Paris can use:
/timeline/Paris,France
A historical request for July 1, 2026 uses:
/timeline/Paris,France/2026-07-01
A historical date range uses:
/timeline/Paris,France/2026-07-01/2026-07-07
When no date is supplied, the Timeline Weather API returns the available forecast data. When historical dates are included, the same API returns historical weather for those dates.
For the complete list of request parameters and available weather elements, see the Timeline Weather API documentation.
Retrieving weather data with webread()
MATLAB’s webread() function reads data from REST web services.
For our first example, we’ll retrieve daily forecast weather for Paris.
apiKey = getenv("VISUAL_CROSSING_API_KEY");
if strlength(apiKey) == 0
error("VISUAL_CROSSING_API_KEY is not set.");
end
url = ...
"https://weather.visualcrossing.com/" + ...
"VisualCrossingWebServices/rest/services/timeline/" + ...
"Paris,France";
options = weboptions( ...
"ContentType", "json", ...
"Timeout", 20);
weather = webread( ...
url, ...
"key", apiKey, ...
"unitGroup", "metric", ...
"include", "days", ...
"elements", ...
"datetime,datetimeEpoch,tempmax,tempmin,conditions", ...
"contentType", "json", ...
options);
Rather than building the complete query string manually, we pass the Weather API parameters directly to webread() as name-value pairs.
For example:
"unitGroup", "metric"
requests metric weather values, while:
"include", "days"
requests daily weather data.
The elements parameter limits the response to:
datetime
datetimeEpoch
tempmax
tempmin
conditions
which are the fields we’ll use in this example.
The weboptions() call also specifies a 20-second timeout:
options = weboptions( ...
"ContentType", "json", ...
"Timeout", 20);
Working with the returned JSON data
The Timeline Weather API returns JSON data.
MATLAB automatically converts the JSON response into MATLAB data structures when webread() processes the result.
For example, the resolved address is available as:
weather.resolvedAddress
The location’s time zone is available as:
weather.timezone
Daily weather records are stored in:
weather.days
For example, the maximum and minimum temperatures for the first returned day can be accessed using:
weather.days(1).tempmax
weather.days(1).tempmin
You can inspect the complete structure directly in MATLAB:
weather
or inspect the first daily record:
weather.days(1)
Creating arrays from the daily weather data
MATLAB makes it easy to convert values from the returned structure into arrays.
For example:
maxTemps = [weather.days.tempmax];
minTemps = [weather.days.tempmin];
creates arrays containing the daily maximum and minimum temperatures.
The Timeline Weather API also provides datetimeEpoch, which represents the date and time as Unix epoch seconds.
We can convert these values into MATLAB datetime values:
dates = datetime( ...
[weather.days.datetimeEpoch], ...
"ConvertFrom", "posixtime");
We now have three arrays:
dates
maxTemps
minTemps
that can be used directly in MATLAB calculations or visualizations.
Plotting weather data
Let’s plot the maximum and minimum temperatures.
plot(dates, maxTemps);
hold on;
plot(dates, minTemps);
hold off;
legend( ...
"Maximum Temperature", ...
"Minimum Temperature");
xlabel("Date");
ylabel("Temperature (°C)");
title("Paris Weather");
grid on;
This produces a simple time-series chart showing the expected daily temperature range.
Once the weather data is loaded into MATLAB, it can be used like any other numeric dataset.
For example, you can combine weather data with:
- Energy consumption
- Agricultural measurements
- Equipment performance
- Sales data
- Transportation data
- Environmental observations
- Sensor data
- Financial or operational data
Retrieving historical weather in MATLAB
The same API and MATLAB code can retrieve historical weather simply by adding dates to the Timeline URL.
For example, to retrieve weather for Paris from July 1 through July 7, 2026:
apiKey = getenv("VISUAL_CROSSING_API_KEY");
url = ...
"https://weather.visualcrossing.com/" + ...
"VisualCrossingWebServices/rest/services/timeline/" + ...
"Paris,France/2026-07-01/2026-07-07";
options = weboptions( ...
"ContentType", "json", ...
"Timeout", 20);
weather = webread( ...
url, ...
"key", apiKey, ...
"unitGroup", "metric", ...
"include", "days", ...
"elements", ...
"datetime,datetimeEpoch,tempmax,tempmin," + ...
"precip,humidity,conditions", ...
"contentType", "json", ...
options);
The resulting data uses the same weather.days structure as the forecast request.
For example:
dates = datetime( ...
[weather.days.datetimeEpoch], ...
"ConvertFrom", "posixtime");
maxTemps = [weather.days.tempmax];
precip = [weather.days.precip];
humidity = [weather.days.humidity];
This consistency makes it easy to write MATLAB analyses that can work with historical or forecast weather data without requiring separate processing logic.
If your primary goal is to explore or download historical datasets rather than retrieve them programmatically, see Visual Crossing Weather Data.
Making the location and dates dynamic
Most MATLAB applications will not use hard-coded locations and dates.
You can build the Timeline URL from variables.
For example:
location = "NewYork,NY";
startDate = "2026-07-01";
endDate = "2026-07-07";
baseUrl = ...
"https://weather.visualcrossing.com/" + ...
"VisualCrossingWebServices/rest/services/timeline/";
url = ...
baseUrl + ...
location + "/" + ...
startDate + "/" + ...
endDate;
The resulting request can then be passed to webread() using the same query parameters shown earlier.
Locations can be specified using addresses, partial addresses, latitude/longitude coordinates, postal codes, and other supported location formats.
When constructing URLs dynamically, make sure that location values containing spaces or reserved URL characters are properly URL encoded.
Retrieving hourly weather
So far, our examples have requested daily weather using:
include=days
To retrieve hourly weather, request:
include=hours
For example:
weather = webread( ...
url, ...
"key", apiKey, ...
"unitGroup", "metric", ...
"include", "hours", ...
"elements", ...
"datetime,datetimeEpoch,temp,precip,humidity,conditions", ...
"contentType", "json", ...
options);
Hourly records are contained within each daily record’s hours structure.
For example:
hours = weather.days(1).hours;
Temperatures for those hours can then be converted into an array:
hourlyTemps = [hours.temp];
and their epoch values can be converted into MATLAB datetimes:
hourlyTimes = datetime( ...
[hours.datetimeEpoch], ...
"ConvertFrom", "posixtime");
You can then plot the hourly temperatures:
plot(hourlyTimes, hourlyTemps);
xlabel("Time");
ylabel("Temperature (°C)");
title("Hourly Temperature");
grid on;
Retrieving current conditions
The Timeline Weather API can also return current weather conditions.
Request current conditions using:
include=current
or combine them with daily weather:
include=current,days
For example:
weather = webread( ...
url, ...
"key", apiKey, ...
"unitGroup", "metric", ...
"include", "current,days", ...
"contentType", "json", ...
options);
Current conditions are then available in:
weather.currentConditions
For example:
currentTemp = ...
weather.currentConditions.temp;
currentHumidity = ...
weather.currentConditions.humidity;
currentConditions = ...
weather.currentConditions.conditions;
Request only the weather elements you need
The Timeline Weather API provides many different weather fields.
MATLAB analyses often require only a subset of those values, so the elements parameter can be used to select the specific fields you need.
For example:
"elements", ...
"datetime,datetimeEpoch,tempmax,tempmin,precip"
is sufficient for an analysis that only needs daily temperatures and precipitation.
Other available elements include weather variables such as:
temp
feelslike
humidity
dew
precip
precipprob
snow
snowdepth
windspeed
winddir
pressure
cloudcover
visibility
solarradiation
solarenergy
uvindex
conditions
See the Timeline Weather API documentation for the complete list of available weather elements.
Handling Weather API errors in MATLAB
Network requests and API requests can fail, so production MATLAB code should handle errors rather than assuming that every request will succeed.
For example:
try
weather = webread( ...
url, ...
"key", apiKey, ...
"unitGroup", "metric", ...
"include", "days", ...
"elements", ...
"datetime,tempmax,tempmin,conditions", ...
"contentType", "json", ...
options);
catch exception
fprintf( ...
"Unable to retrieve weather data:\n%s\n", ...
exception.message);
rethrow(exception);
end
Errors can occur because of issues such as:
- An invalid API key
- An invalid location
- Invalid dates or parameters
- Account usage limits
- Network connectivity problems
- Request timeouts
When debugging a Weather API request, it can also be useful to build and test the equivalent request using the Visual Crossing Query Builder before reproducing it in MATLAB.
Using US units instead of metric
The examples in this article use:
"unitGroup", "metric"
To request US weather units instead, use:
"unitGroup", "us"
The unit group controls the units used for values including temperature, precipitation, wind speed, visibility, and other weather elements.
Choose the unit group appropriate for your MATLAB analysis before processing the returned data.
Complete MATLAB example
The following script combines the main steps from this tutorial into a single example:
apiKey = getenv("VISUAL_CROSSING_API_KEY");
if strlength(apiKey) == 0
error("VISUAL_CROSSING_API_KEY is not set.");
end
url = ...
"https://weather.visualcrossing.com/" + ...
"VisualCrossingWebServices/rest/services/timeline/" + ...
"Paris,France";
options = weboptions( ...
"ContentType", "json", ...
"Timeout", 20);
try
weather = webread( ...
url, ...
"key", apiKey, ...
"unitGroup", "metric", ...
"include", "days", ...
"elements", ...
"datetime,datetimeEpoch,tempmax,tempmin," + ...
"precip,conditions", ...
"contentType", "json", ...
options);
catch exception
fprintf( ...
"Unable to retrieve weather data:\n%s\n", ...
exception.message);
rethrow(exception);
end
dates = datetime( ...
[weather.days.datetimeEpoch], ...
"ConvertFrom", "posixtime");
maxTemps = [weather.days.tempmax];
minTemps = [weather.days.tempmin];
plot(dates, maxTemps);
hold on;
plot(dates, minTemps);
hold off;
legend( ...
"Maximum Temperature", ...
"Minimum Temperature");
xlabel("Date");
ylabel("Temperature (°C)");
title( ...
"Weather for " + ...
string(weather.resolvedAddress));
grid on;
This example:
- Reads the API key from an environment variable.
- Retrieves daily weather using
webread(). - Automatically parses the JSON response into MATLAB structures.
- Converts Timeline epoch timestamps into MATLAB
datetimevalues. - Extracts daily maximum and minimum temperatures.
- Plots the resulting weather time series.
Going further with weather data in MATLAB
Once Visual Crossing weather data is available in MATLAB, you can use MATLAB’s analytical and visualization capabilities to explore relationships between weather and other datasets.
Possible applications include:
- Historical weather analysis
- Energy demand modeling
- Renewable energy analysis
- Agricultural research
- Transportation analysis
- Environmental modeling
- Operational planning
- Machine learning
- Statistical analysis
- Weather visualization
The Visual Crossing Weather API provides programmatic access to historical weather, current conditions, forecasts, alerts, and other weather information.
For interactive access to historical and forecast datasets, see Visual Crossing Weather Data.
For detailed request options, response structures, and available weather fields, see the Timeline Weather API documentation.
Summary
MATLAB’s built-in web-service and JSON support makes it easy to incorporate weather data into MATLAB analyses.
The basic process is:
- Obtain a Visual Crossing Weather API key.
- Build a Timeline Weather API URL for the required location and dates.
- Use
webread()to retrieve the weather data. - Let MATLAB automatically convert the JSON response into structures.
- Extract daily, hourly, or current weather values.
- Convert timestamps into MATLAB
datetimevalues where required. - Use the resulting data in calculations, charts, models, and other analyses.
Because the Timeline Weather API provides historical, current, and forecast weather through a consistent interface, the same MATLAB techniques can support a wide variety of weather-data analysis projects.

