why this code is not running ? the workspace remains empty.

m = zeros(1,163);
count = 1;
flag= 0;
while 1
r = randi([1,326]);
for i = 1:1:count
if(m(1,i)==r)
flag = 1;
end
end
if(flag==0)
m(1,count)=r;
count=count+1;
end
if(count==163)
break;
end
end

 Réponse acceptée

James Tursa
James Tursa le 13 Juil 2017
Modifié(e) : James Tursa le 13 Juil 2017
Once flag gets set to 1, you don't ever reset it to 0 so you effectively disable the rest of your code and count ceases to increment and you have an infinite loop. So move the flag=0 line to inside your loop. E.g.,
m = zeros(1,163);
count = 1;
while 1
r = randi([1,326]);
flag = 0; % <-- Moved to here
for i = 1:1:count
if(m(1,i)==r)
flag = 1;
end
end
if(flag==0)
m(1,count)=r;
count=count+1;
end
if(count==163) % <-- Is this really what you want?
break;
end
end
Also, your code exits the loop before setting the last element. If you want to set that last element, change your if(count==163) test to if(count==164).
Finally, it looks like you are simply wanting to generate an array of random non-repeating integers between 1 and 326. This entire code could be reduced to this one line:
m = randperm(326,163);
Or if you have an older version of MATLAB:
m = randperm(326);
m = m(1:163);

1 commentaire

thanks a lot sir. can you please tell me how can I work with a .csv file ? it consists "att_1","att_2" like this alpha numeric characters . So its being very difficult for me to read and manipulate this through code .

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by