reading 10 values randomly from txt file
조회 수: 4 (최근 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!