% test of broadcast

clearvars;

N = 20000;
fn = 1;  % = 1/2/3/4
ntest = 10;

% setup
a = zeros(N, 1, 'double');
b = zeros(N, 1, 'double');
c = zeros(N, N, 'double');
for i = 1 : N
	a(i) = double(i);
	b(i) = double(i);
end

tic

% calculation
for i = 1 : ntest
	if     fn == 1
		c = fn1(a, b);
	elseif fn == 2
		c = fn2(a, b);
	elseif fn == 3
		c = fn3(a, b);
	elseif fn == 4
		c = fn4(a, b);
	end
end

dt = toc / ntest;
fmt = '(%d) N=%d, %.3f[sec], %e, %e\n';
exact = N^2 * (N + 1);
fprintf(fmt, fn, N, dt, sum(c(:)), exact);

% (1) j, i loop
function c = fn1(a, b)
	n = length(a);
	for j = 1 : n
		for i = 1 : n
			c(i, j) = a(i) + b(j);
		end
	end
end

% (2) j loop
function c = fn2(a, b)
	n = length(a);
	for j = 1 : n
		c(:, j) = a + b(j);
	end
end

% (3) i loop
function c = fn3(a, b)
	n = length(a);
	for i = 1 : n
		c(i, :) = a(i) + b;
	end
end

% (4) broadcast
function c = fn4(a, b)
	n = length(a);
	c = reshape(a, n, 1) + reshape(b, 1, n);
end
