Generating all possible nxn matricies for a given range of element values.

1 view (last 30 days)
What I want to do is generate all possible nxn matricies for a given range of elements.
Example: Range={1,2} Matrix= 2x2
where the output is all possible 2x2 matricies with each element ranging from 1 to 2.
Generating a shell matrix is easy as zeros(n,n) handles it. From here getting the program to cycle through all possible entries has been unsuccessful. Converting the matrix to an array and then basically counting in base whatever my max range value is has been marginally successful, but that only works when entries are from 0 to some natural number.
Ideally the program should work like this.
Inputs: Size of the matrix (n) Min. Range (a) Max. Range (b)
Outputs: All possible nxn matricies with element values ranging from a to b.
This program will only need to handle whole numbers.
Thank you for any help or pointers you can offer.
  1 Comment
Teja Muppirala
Teja Muppirala on 31 Oct 2012
Converting the matrix to an array and then basically counting in base whatever my max range value is has been marginally successful, but that only works when entries are from 0 to some natural number.
I am not sure what level of success you mean by marginal, but if you could get it to work for 0 to something, then why don't you just do that from 0 to a-b and then add a to whatever you get?

Sign in to comment.

Answers (1)

Matt J
Matt J on 31 Oct 2012
Edited: Matt J on 31 Oct 2012
args=repmat({a:b},1,n^2);
[data{1:n^2}]=ndgrid(args{:});
data=cell2mat(cellfun(@(c) c(:),data,'uni',0)).';
result=reshape(data,n,n,[]);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!