Matlab中datetime类型外减法运算失败:原因及解决方法
Great question! Let's break this down clearly:
Core Reason
The key difference comes down to MATLAB's broadcast support for different data types:
- Numeric arrays (since R2016b) have built-in implicit broadcasting for arithmetic operations. When two arrays have compatible dimensions (e.g.,
1x3and2x1—each dimension pair is either equal or one is 1), MATLAB automatically expands them to the same size before computing the operation. - For
datetime(andNaT, which is the datetime equivalent ofNaN) subtraction: This operation returns adurationvalue representing the time difference. MATLAB does not implement implicit broadcasting for non-scalar, mismatched-size datetime arrays. It only allows operations where inputs are the same size, or one is a scalar. That's why you get the error: "Data inputs must be the same size, or any of them can be a scalar."
Solutions
You have two reliable ways to replicate the numeric-style broadcast subtraction for datetime/NaT:
1. Manual Array Expansion with repmat
Manually resize both arrays to match the target size (in your case, 2x3) using repmat, then perform the subtraction:
% Define your inputs nat_row = NaT(1, 3); nat_col = NaT(2, 1); % Expand each array to the common size nat_row_expanded = repmat(nat_row, size(nat_col, 1), 1); nat_col_expanded = repmat(nat_col, 1, size(nat_row, 2)); % Perform the subtraction result = nat_row_expanded - nat_col_expanded;
2. Use bsxfun for Implicit Broadcast
The bsxfun function is designed to apply element-wise operations to arrays with compatible dimensions, and it works with datetime types. It handles the expansion automatically, just like numeric broadcasting:
% Directly compute the broadcast subtraction result = bsxfun(@minus, NaT(1, 3), NaT(2, 1));
This will produce exactly the same structure as the numeric array example—you'll get a 2x3 matrix of NaT (since subtracting NaT from NaT returns NaT), which matches the behavior you expected.
To test with valid datetimes (not just NaT):
dt_row = datetime(2024, 1, 1:3); % 1x3: [2024-01-01, 2024-01-02, 2024-01-03] dt_col = datetime(2024, 1, [1;2]); % 2x1: [2024-01-01; 2024-01-02] result = bsxfun(@minus, dt_row, dt_col);
The output will be:
0 days 1 day 2 days -1 day 0 days 1 day
Which aligns perfectly with the numeric subtraction result, just as duration values.
内容的提问来源于stack exchange,提问作者Dims

