117 views (last 30 days)

Hello again.

I want to make a matrix with random numbers that do not repeat in each row in a k X p matrix

and can be modified depending on inputs.

So far i have a code:

clc

k=input('# rows ');

p=input('# columns')

S=randperm(p);

S=S(1:(k*p));

S=reshape(S,k,p)

This works some times but not all the times.

Please help?

Walter Roberson
on 14 Apr 2019

Old trick that randperm() used to implement:

[~, S] = sort(rand(k, p), 2);

Steven Lord
on 21 Jun 2019

You have a requirement that no row may contain the same number twice. Can different rows in the same matrix contain the same number? So in the example below, A would not be acceptable (the second row has two 3's) but B would be acceptable (the first and second rows each have 2)?

A = [1 2; 3 3];

B = [1 2; 2 3];

If so, call randperm once for each row, telling it to generate size(B, 2) numbers from 1 to your upper limit.

nrows = 10;

ncols = 7;

maxvalue = 100;

A = zeros(nrows, ncols);

for whichrow = 1:nrows

A(whichrow, :) = randperm(maxvalue, ncols);

end

If you call rng default immediately before calling that code the resulting matrix should have three rows that contain the number 4 and three rows that contain 89, but that neither 4 nor 89 repeat in the same row.

Rainaire Hansford
on 21 Jun 2019

Walter Roberson
on 28 Jun 2019

By the way, there are vectorized solutions that can work when the amount of data is not big.

Walter Roberson
on 28 Jun 2019

Opportunities for recent engineering grads.

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

Start Hunting!
## 4 Comments

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/456326-random-number-with-no-repeats-in-set-matrix#comment_694024

⋮## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/456326-random-number-with-no-repeats-in-set-matrix#comment_694024

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/456326-random-number-with-no-repeats-in-set-matrix#comment_696101

⋮## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/456326-random-number-with-no-repeats-in-set-matrix#comment_696101

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/456326-random-number-with-no-repeats-in-set-matrix#comment_696105

⋮## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/456326-random-number-with-no-repeats-in-set-matrix#comment_696105

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/456326-random-number-with-no-repeats-in-set-matrix#comment_696106

⋮## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/456326-random-number-with-no-repeats-in-set-matrix#comment_696106

Sign in to comment.