help for fprintf command !!!!!!!

4 ビュー (過去 30 日間)
yasemin sirin
yasemin sirin 2017 年 3 月 22 日
回答済み: yasemin sirin 2017 年 3 月 22 日
ı want to see random number generated in 1 run
for i = 1 : n
a=rand(1);
city_1 = round(length(inputcities)*a);
fileID = fopen('rndm.txt','w+');
for i=1:length(a)
fprintf(fileID,'%6.4f\n',a);
end
fclose(fileID);
when ı run programe it writes only one value for a.. but ı want it to write all rondom numbers during one run
thanks..

回答 (3 件)

Jan
Jan 2017 年 3 月 22 日
編集済み: Jan 2017 年 3 月 22 日
fileID = fopen('rndm.txt','w+');
for i = 1 : n
a = rand(1);
city_1 = round(length(inputcities)*a); % Not used at all
fprintf(fileID, '%6.4f\n', a);
end
fclose(fileID);
Open the file once before the loop. You do not need the for i=1:length(a) loop, when a has one element only.
This might be easier:
fileID = fopen('rndm.txt', 'w+');
a = rand(1, n);
fprintf(fileID, '%6.4f\n', a);
fclose(fileID);

ES
ES 2017 年 3 月 22 日
編集済み: ES 2017 年 3 月 22 日
You are opening the file in write mode inside a for loop. So everytime the file gets overwritten.
Open the file (fileID = fopen('rndm.txt','w+');) before the for loop.
fileID = fopen('rndm.txt','w+');
for i = 1 : n
a=rand(1);
city_1 = round(length(inputcities)*a);
for i=1:length(a)
fprintf(fileID,'%6.4f\n',a);
end
end
fclose(fileID);

yasemin sirin
yasemin sirin 2017 年 3 月 22 日
thanks for your answers....ı open the file outside the loop and ı changed w+ to a+ then i can get whole set of random numbers.... again thanks so much

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by