reading 10 values randomly from txt file
2 ビュー (過去 30 日間)
古いコメントを表示
I want to know how to read 10 random values from txt file
1)fid = fopen('data01.txt')
will open the 'data01.txt' file
2)h= fscanf(fid,'%d')'
will read data from the file specified by fid which is 'data01.txt', converts it according to the specified format string which is %d, and returns it in matrix h.
3)fclose(fid)
fclose will close the specified file which was opened. and in this code the file to be closed is 'data01.txt'
D= diag(h)
i dont know what to do next from here, please help
2 件のコメント
Jan
2021 年 9 月 10 日
What is random in your case? The values of the numbers? Does the file has 100 elements and you want to select 10 of them randomly? With or without repetitions?
回答 (1 件)
Chunru
2021 年 9 月 11 日
% Generate the text file
n = 200; % 5000
x = randi(100, n,1);
fout = fopen('test.tx', 'wt');
fprintf(fout, '%f\n', x);
fclose(fout);
% Read the data from text file
fid = fopen('test.tx', 'rt');
h = fscanf(fid, '%f ', [1, inf])';
fclose(fid);
% Now randomly pick 10 numbers from n
idx = randperm(n, 10);
x = h(idx)
1 件のコメント
Jan
2021 年 9 月 11 日
編集済み: Jan
2021 年 9 月 11 日
Exactly. I'd omit the 't' in the fopen. All it does is creating different line breaks under Windows and Linux. Only the Notepad shipped with Windows until 2019 was not able to understand Linux line breaks, but all other editors understand both versions - e.g. Matlab's editor since 2002.
The text mode has same strange effects. E.g. the number of characters after reading need not be the number of bytes of the file, because \backspace removes a formerly read byte and ctrl-Z (0x1A) is interpreted as end of file, even if further characters are following. Reading in text mode is slower than in binary mode. But the biggest drawback is the platform dependent output.
I consider the text mode of files as mid-age technology worth to be retired.
参考
カテゴリ
Help Center および File Exchange で Get Started with MATLAB についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!