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

 採用された回答

James Tursa
James Tursa 2017 年 7 月 13 日
編集済み: James Tursa 2017 年 7 月 13 日

0 投票

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 件のコメント

debmalya roy
debmalya roy 2017 年 7 月 14 日
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 .

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by