help n=12 for I=1:n p(I) =rand p(I) =28×p(I) p(I)=ceil(p(I)) end I need to put constraint on this code must be theres no redanandnt values ..so if n=28 p will be all the numbers from 1:28 but in random

n=12
for I=1:n
p(I) =rand
p(I) =28×p(I)
p(I)=ceil(p(I))
end
I need to put constraint on this code must be theres no redanandnt values ..so if n=28 p will be all the numbers from 1:28 but in random

1 Comment

Please keep code in the body of the question not in the title. The title should be a short description of the problem.
Also please use the {} Code block to include formatted code.

Answers (2)

‘I need to put constraint on this code must be theres no redanandnt values ..so if n=28 p will be all the numbers from 1:28 but in random’
The easiest way is to use the randperm function:
n = 12;
p = randperm(n);

5 Comments

this not work cause the numbers will be between 1:12 but I need to generate 12 integer elementes there values between 1 to28 but at random like this [3 ,26 ,1 ,19 ,3 ,12 ,2, 15,9 ,11,23,18] without any repeated values
Ah yes, I thought there must be some builtin way of doing this, but I just couldn't remember it!!
randperm( 28, 12 )
would be what you would need to get 12 distinct values between 1 and 28.
@Adam — Thank you for your Comment!
Our friendly randperm appears frequently in Answers. That’s how I learned about it, since I don’t otherwise need to use it that often.
@maha ismail — If you don’t have randperm, use Matt Fig’s File Exchange contribution COMBINATOR.
Something like this would work:
nums = 1:28;
n = 28;
p = zeros(1,n);
count = numel( nums );
for i = 1:n
idx = randi(count);
p(i) = nums( idx );
nums( idx ) = [];
count = count - 1;
end
Not necessarily the most efficient way of doing it, but it will guarantee uniqueness so long as n is at most 28 (or whatever value you set as the maximum of nums.

2 Comments

my matlab is version 6.5 doesn't not have randi or randperm instructions ..I have only rand code can you rewrite the same program but with rand instruction?
replace:
randi( count )
with
round( rand( count ) * n )
and I think that should give you the correct answer.

This question is closed.

Asked:

on 10 Feb 2015

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!