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

Matlab中datetime类型外减法运算失败:原因及解决方法

Why Datetime/NaT Subtraction Fails with Broadcast (Unlike Numeric Arrays) in MATLAB

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., 1x3 and 2x1—each dimension pair is either equal or one is 1), MATLAB automatically expands them to the same size before computing the operation.
  • For datetime (and NaT, which is the datetime equivalent of NaN) subtraction: This operation returns a duration value 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:22:35