Azzera filtri
Azzera filtri

reading 10 values randomly from txt file

2 visualizzazioni (ultimi 30 giorni)
RISHNEEL NARAYAN
RISHNEEL NARAYAN il 10 Set 2021
Modificato: Jan il 11 Set 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 Commenti
Jan
Jan il 10 Set 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 il 11 Set 2021
5000 elements in the txt file, just select 10 random values for calculation. Without repetitions

Accedi per commentare.

Risposte (1)

Chunru
Chunru il 11 Set 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 Commento
Jan
Jan il 11 Set 2021
Modificato: Jan il 11 Set 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.

Accedi per commentare.

Categorie

Scopri di più su Get Started with MATLAB in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by