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
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?
RISHNEEL NARAYAN
RISHNEEL NARAYAN 2021-9-11
5000 elements in the txt file, just select 10 random values for calculation. Without repetitions

请先登录,再进行评论。

回答(1 个)

Chunru
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)
x = 10×1
7 23 48 100 30 40 73 59 99 17
  1 个评论
Jan
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 CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by