MATLAB Answers

Create custom matrix with user-defined parameters

15 views (last 30 days)
Blake Seaton
Blake Seaton on 3 Jul 2020
Commented: Blake Seaton on 14 Jul 2020 at 6:15
Hi,
I would like help creating a custom matrix that follows this pattern:
[1 1 -1 1;
1 1 1 -1;
1 2 -1 1;
1 2 1 -1;
1 3 -1 1;
1 3 1 -1;
2 1 -1 1;
2 1 1 -1;
2 2 -1 1;
2 2 1 -1;
2 3 -1 1;
2 3 1 -1;
3 1 -1 1;
3 1 1 -1;
3 2 -1 1;
3 2 1 -1;
3 3 -1 1;
3 3 1 -1;
4 1 -1 1;
4 1 1 -1;
4 2 -1 1;
4 2 1 -1;
4 3 -1 1;
4 3 1 -1]
I want the maximum number to which the first two columns count to be user-determined (e.g., x and y, respectively).
In the above example, x = 4 and y = 3.
Column one counts to x, repeating each integer (2y) times.
Column two counts to y, repeating each integer twice.
Columns three and four alternate between -1 and 1 for the entirety of the matrix.
So the total number of rows for the matrix is always (x * y * 2) which equals 24 in the above example.
Thanks in advance!

  2 Comments

Blake Seaton
Blake Seaton on 3 Jul 2020
Sorry, I'm not sure what more I can provide. I would like a block of code that will take a number for x and a number for y and create a matrix with the posted pattern and explanation. There are roundabout ways of getting it done, but because I'm still somewhat of a novice, I can't seem to come up with an elegant way to do it.

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 3 Jul 2020
x = 4 ;
y = 3 ;
[ X, Y ] = meshgrid( 1 : x, 1 : y ) ;
Alternator = repmat( ( - 1 ) .^ ( 1 : numel( X ) ).', 1, 2) ;
z = [ X( : ), Y( : ) ] ;
Wanted = [ repelem( z, 2, 1 ), Alternator( : ) * [ 1, - 1 ] ]

  4 Comments

Show 1 older comment
Blake Seaton
Blake Seaton on 14 Jul 2020 at 6:01
Follow up question:
How could this be modified so that the first two columns are never the same number? Following the same pattern as the original question, the end result would look like:
[1 2 -1 1;
1 2 1 -1;
1 3 -1 1;
1 3 1 -1;
2 1 -1 1;
2 1 1 -1;
2 3 -1 1;
2 3 1 -1;
3 1 -1 1;
3 1 1 -1;
3 2 -1 1;
3 2 1 -1;
4 1 -1 1;
4 1 1 -1;
4 2 -1 1;
4 2 1 -1;
4 3 -1 1;
4 3 1 -1]
madhan ravi
madhan ravi on 14 Jul 2020 at 6:08
Wanted( Wanted(:, 1) ~= Wanted(:, 2), :)

Sign in to comment.

More Answers (0)


Translated by