Home > Net >  MATLAB Broadcasting for unifrnd
MATLAB Broadcasting for unifrnd

Time:11-08

I am coming back from NumPy to MATLAB and don't quite have the hang of the broadcasting here. Can someone explain to me why the first one fails and the second (more explicit works)? After my understanding, x0 and x1 are both 1x2 arrays and it should be possible to extend them to 5x2.

n_a = 5;
n_b = 2;

x0 = [1, 2];
x1 = [11, 22];

% c = unifrnd(x0, x1, [n_a, n_b])
% Error using unifrnd
% Size information is inconsistent.
% c = unifrnd(x0, x1, [n_a, 1])  % also fails

c = unifrnd(ones(n_a, n_b) .* x0, ones(n_a, n_b) .* x1, [n_a, n_b])
% works

CodePudding user response:

There is a size verification within the unifrnd function (you can type open unifrnd in the command line to see the function code). It sends the error if the third input is not coherent with the size of the first 2 inputs:

[err, sizeOut] = internal.stats.statsizechk(2,a,b,varargin{:});
if err > 0
    error(message('stats:unifrnd:InputSizeMismatch'));
end

If you skip this part, though (as in if you create a custom function without the size check), both your function calls that fail will actually work, due to implicit expansion. The real question is whether calling the function this way makes sense.

TL;DR : It is not the broadcasting that fails, it is the function that does not allow you these sets of inputs

CodePudding user response:

unifrnd essentially calls rand and applies scaling and shifting to the desired interval. So you can use rand and do the scaling and shifting manually, which allows you to employ broadcasting (singleton expansion):

c = x0   (x1-x0).*rand(n_a, n_b);
  • Related