In general I'm defining a matlab fnction which takes the name of a file containing some numbers, one per line, reads the data in, and then returns the data in an array.
function x = readdata(filename)
This function takes the name of a file contained in the
% character array "filename", read in the data from it, and then
% return the resulting numbers in the 1-dimensional array x. The
% array x can be n x 1 or 1 x n, where n is the number of numbers
% in the data file.
%
% If the data file cannot be found, this function should print a
% warning (using the disp() function) and return x as an empty
% array. If the data file can be found but is empty or contains
% only comments (lines starting with the Matlab comment indicator %),
% this function should return an empty array x with no warning
% message.
%
%
%I'm not sure how to check if a file exist (while they are in same folder).
%I tried if exist(filename,'file') but this is not working
This is what I have now:
function x = readdata(file)
fid = fopen(file);
tline = fgets(fid);
while isnumeric(tline)
disp(tline)
tline = fgets(fid)
Thanks
I would start by taking a look at the documentation that you could find here for reading in line-by-line. It even gives a sample code that you could start with:
Reading Data Line-by-Line
MATLAB provides two functions that read lines from files and store them in
string vectors: fgetl and fgets. The fgets function copies the newline
character to the output string, but fgetl does not.
The following example uses fgetl to read an entire file one line at a time.
The function litcount determines whether an input literal string (literal)
appears in each line. If it does, the function prints the entire line preceded
by the number of times the literal string appears on the line.
function y = litcount(filename, literal)
% Search for number of string matches per line.
fid = fopen(filename);
y = 0;
tline = fgetl(fid);
while ischar(tline)
matches = strfind(tline, literal);
num = length(matches);
if num > 0
y = y + num;
fprintf(1,'%d:%s\n',num,tline);
end
tline = fgetl(fid);
end
fclose(fid);
You should be able to replace what is inside the while loop with what you are looking to do.
Of note is that the fgets and fgetl functions return character arrays (strings). Thus, you'll need to first check whether the line is a comment, and then, if not, convert the string to a numeric value using something along the lines of str2double.
As for checking existence of a file, exist(filename,'file') is definitely what you want. Its documentation is found here.
You should be able to do something like:
if ~exist(filename,'file')
% Do something... I suggest the warning function, disp could be used too...
warning('The file cannot be found!')
return
end
Related
I am trying to read a text file and store the data inside into structs and I am interested in finding out how to ignore the first 4 lines (text header) in the text file.
This is the text file:
text file
I am only going to need the numeric values from it (year int, month int, max double, etc.) and ignore the four text lines above them.
This is the code I use to store the values as a collection of structs:
code
You can use func dropFirst(_ n: Int) to skip initial lines:
let lines = contents.components(separatedBy: "\n")
for line in lines.dropFirst(4) {
// ...
}
dropFirst(4) returns an “array slice” with all but the first 4
elements in the lines array, which means that the element storage
is not duplicated.
If it's always 4 lines then #Martin R has a good answer, otherwise you could see if the first word can be converted to an int like
for line in filtered {
let x = line.components(separatedBy: " ")
guard let year = Int(x[0] else {
continue
}
....
I have an array called temp containing double-precision values with dimensions 240×20×10428 . I would like to write it to a text file. I tried the following:
dlmwrite(['e:\temp\', str, '.txt'], temp, 'precision', 10);
now the problem is how to add \r\n\r\n string(two enter pressed key) after each first dimension (we have 240th of this dimension) in the text file? what should I have done? I want to have this format after all:
0.324235,...(20*10428 numbers),0.4363423,\r\n\r\n,
0.5467354,...(20*10428 numbers),0.346564,...
NOTE: this array come from .nc files and I want to convert them into .txt file using this way
The handy-dandy canned routines that ship with MATLAB are actually quite limited when it comes to customizability. Whenever you have some file writing to do with a custom format, it comes in handy to know how to do it yourself:
% Open file for writing, safely
fid = fopen(fullfile('e:\temp\', str, '.txt'), 'w');
OC = onCleanup(#() any(fopen('all')==fid) && fclose(fid));
% Simply loop through all rows
for ii = 1:size(temp,1)
% Format the numbers, with comma as separator
line = sprintf('%.10f,', temp(ii,:)); % (trick to concatenate last dimension into second one)
line(end) = []; %(remove last comma)
% Print this line, adding two PC-type newlines
fprintf(fid, '%s\r\n\r\n', line);
end
% Clean up
fclose(fid);
I am trying to store the longest resultant string after using the function strsplit unable to do so
eg: I have input strings such as
'R.DQDEGNFRRFPTNAVSMSADENSPFDLSNEDGAVYQRD.L'or
'L.TSNKDEEQRELLKAISNLLD'
I need store the string only between the dots (.)
If there is no dot then I want the entire string.
Each string may have zero, one or two dots.
part of the code which I am using:
for i=1:700
x=regexprep(txt(i,1), '\([^\(\)]*\)','');
y=(strsplit(char(x),'.'));
for j=1:3
yValues(1,j)=y{1,j};
end
end
But the string yValues is not storing the value of y, instead showing the following error:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
What am I doing wrong and are there any suggestions on how to fix it?
The issue is that y is a cell array and each element contains an entire string and it therefore can't be assigned to a single element in a normal array yvalues(1,j).
You need yvalues to be a cell array and then you can assign into it just fine.
yValues{j} = y{j};
Or more simply
% Outside of your loop
yValues = cell(1,3);
% Then inside of your loop
yValues(j) = y(j);
Alternately, if you just want the longest output of strsplit, you can just do something like this.
% Split the string
parts = strsplit(mystring, '.');
% Find the length of each piece and figure out which piece was the longest
[~, ind] = max(cellfun(#numel, parts));
% Grab just the longest part
longest = parts{ind};
My objective here is to read from a text file filenames for images as strings, EX: myImage.jpg.
I have this block of code that reads how many lines are in the file.
listOfImages = fopen('translate.txt', 'r');
count = 0;
%This while loop calculates the amount of lines within our text file
while ~feof(listOfImages)
line = fgetl(listOfImages);
if isempty(line) | strncmp(line, '%', 1)
continue
end
count = count+1;
end
numberOfLines = count;
now using numberOfLines how do i put each line into some sort of array of strings using a for loop.
so,
for i = 1:numberOfLines,
DO CODE
end
what do i put here to make it so i can read my translate.txt file row by row?
thanks
Because the file names will likely be different lengths you will want to use a cell instead of a matrix.
Try the following:
% read the text into names, breaking on newlines
fid = fopen('translate.txt');
names = textscan(fid,'%s','delimiter','\n');
names = names{1};
fclose(fid);
for f = 1:length(names)
disp(names(f));
end
I want to store user inputs in an array, but when a person enters a new number, the previous input gets replaced. How can I create such an array in Matlab such that I can store all inputs without replacement? I am a beginner so bear with me
Thanks
You simply need to copy the contents of the input buffer into a data struct that won't be overwritten.
Cell arrays are good for that (see the userInputs variable below) . Without better knowledge of your code, I'm guessing the user input is stored in a variable named buffer. Here's how I would do it:
% a new buffer comes in
userInputs{iInput} = buffer;
iInput = iInput + 1;
% keep looking for more inputs
Good luck!
If you want a numeric matrix here is an example:
n = 2; %# number of rows
m = 3; %# number of columns
out = zeros(n,m); %# the output
k = 1; %# counter
while k <= n*m
x = input('Enter a number or Enter to stop: ');
if isempty(x)
break
else
out(k)=x;
end
k=k+1;
end
disp(xx)