The first thing your code should do is check if the inputs are compatible and return an throw an error message explaining the problem otherwise:
assert(n1 + n2 + n3 == dim^2, 'the count of elements must match the size of the matrix);
Or you could change the signature of your function so that it doesn't ask for dim since it's redundant (it's the square root of n1+n2+n3, and that sum is not a square, you throw an error).
Secondly, to generate random integers you shoul use randi(d) unstead of round(rand*d)+1.
The biggest problem with your code is that it doesn't ensure that the different coordinates you generate are all different, so it is extremely likely that you're going to fill the same spot more than once (and hence miss other spots).
The easiest way to do what you want:
function matrice = hyperImage(dim, n1 ,n2 ,n3)
assert(n1 + n2 + n3 == dim^2, 'the count of elements must match the size of the matrix);
filler = repelem([1 2 3], [n1 n2 n3]);
matrice = reshape(filler(randperm(numel(filler))), dim, dim);
end
Best Answer