Skip to content

Fix datasample MATLAB compatibility - #505

Merged
pr0m1th3as merged 1 commit into
gnu-octave:mainfrom
sahilphad07-sudo:fix-datasample-matlab-behavior
Sep 24, 2026
Merged

pr0m1th3as merged 1 commit into
gnu-octave:mainfrom
sahilphad07-sudo:fix-datasample-matlab-behavior

Conversation

@sahilphad07-sudo

Copy link
Copy Markdown
Contributor

datasample did not match MATLAB behavior for invalid and infinite sampling weights.

NaN and all-zero weights were not rejected during validation, and Inf weights could lead to incorrect sampling because normalizing infinite values produced invalid probabilities.

This change updates weight validation and sampling logic to handle these cases consistently with MATLAB.

Before

octave:> datasample(1:5, 2, 'Weights', [NaN 1 1 1 1])
ans =

   5   5

octave:> datasample(1:5, 2, 'Weights', [Inf 1 1 1 1], 'Replace', true)
ans =

   5   5

After

octave:> datasample(1:5, 2, 'Weights', [NaN 1 1 1 1])
error: datasample: the sampling weights must be defined as a vector of positive values

octave:> datasample(1:5, 2, 'Weights', [Inf 1 1 1 1], 'Replace', true)
ans =

   1   1

octave:> datasample(1:5, 2, 'Weights', [Inf 1 1 1 1], 'Replace', false)
ans =

   1   2

MATLAB Behavior

  • NaN weights are rejected.
  • All-zero weights are rejected.
  • An Inf weight is always selected when sampling with replacement.
  • With replacement disabled, the Inf-weighted element is selected first.

Regression Tests Added

  • NaN weights
  • All-zero weights
  • Inf weights with replacement
  • Inf weights without replacement

Test Results

All existing and new datasample BISTs pass:

PASSES 26 out of 26 tests.

@pr0m1th3as
pr0m1th3as merged commit 2125e4a into gnu-octave:main Sep 24, 2026
8 checks passed
pr0m1th3as added a commit that referenced this pull request Sep 24, 2026
  Elements sharing an Inf weight are equally likely, where MATLAB draws
  only the first of them; the help text says so.
  * inst/Data_Manipulation/datasample.m: validate the weights through one
  variable; reword the message to non-negative values with at least one
  positive; indent the sampling loop without replacement; describe zero
  and Inf weights in the help text; match every weights error in full;
  add tests for several Inf weights, with and without replacement.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants