Azzera filtri
Azzera filtri

How to assign the number of filled columns of a text file as the value of a variable

2 visualizzazioni (ultimi 30 giorni)
Hello,
I am trying to open the file nt.txt, with the goal of assigning the number of columns to the variable nu. Right now, I have the following code:
fid=fopen('E:\A\nt.txt');
g = textscan(fid,'%d','delimiter','\n');
nu=length(g)
fclose(fid)
However, it does not seem to work. Could someone help me?
Best regards,
Hugo

Risposta accettata

Walter Roberson
Walter Roberson il 21 Set 2020
detectImportOptions() might be your easiest method.
Otherwise,
fid = fopen('E:\A\nt.txt');
while true
thisline = fgetl(fid);
if ~ischar(thisline); break; end %end of file
thisline = strtrim(thisline);
if ~isempty(thisline); break; end %found a line
end
fclose(fid);
if ~ischar(thisline)
nu = 0;
else
nu = length(regexp(thisline, '\S+', 'split'));
end
This code assumes that columns are delimited by whitespace (otherwise your %d format would have failed).
The code looks for the first line of the file that contains something that is not whitespace, splits it into fields, and assumes that the number of columns is however many fields were found.
If the file has no non-empty lines, then nu is assigned 0.

Più risposte (0)

Categorie

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

Tag

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by