Clear Filters
Clear Filters

reading 10 values randomly from txt file

2 views (last 30 days)
RISHNEEL NARAYAN
RISHNEEL NARAYAN on 10 Sep 2021
Edited: Jan on 11 Sep 2021
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 Comments
Jan
Jan on 10 Sep 2021
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 on 11 Sep 2021
5000 elements in the txt file, just select 10 random values for calculation. Without repetitions

Sign in to comment.

Answers (1)

Chunru
Chunru on 11 Sep 2021
% 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 Comment
Jan
Jan on 11 Sep 2021
Edited: Jan on 11 Sep 2021
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.

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!