I'm writting a Matlab code that generates an array number and it should replace that each number in a text file (that already exists) and replace all instances with that. The number should be in string format. I've achieved this:
ita='"';
for i=1:size(z,2)
word_to_replace=input('Replace? ','s');
tik=input('Replacement? ','s');
coluna=input('Column? ');
files = dir('*.txt');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
fh = fopen(files(i).name,'w');
val=num2str(z(i,coluna));
word_replacement=strcat(tik,val,ita);
contents = regexprep(contents,'word_to_replace','word_replacement');
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end
end
I want the code to open the file#1 ('file.txt'), find and replace all instances 'word_replacement' with 'word_to_replace' and save to the same file. The number of txt files is undefined, it could be 100 or 10000.
Many thanks in advance.
The problem with your code is the following statement:
contents = regexprep(contents,'word_to_replace','word_replacement');
You are using regular expressions to find any instances of word_to_replace in your text files and changing them to word_replacement. Looking at your code, it seems that these are both variables that contain strings. I'm assuming that you want the contents of the variables instead of the actual name of the variables.
As such, simply remove the quotations around the second and third parameters of regexprep and this should work.
In other words, do this:
contents = regexprep(contents, word_to_replace, word_replacement);
Related
My matlab function is in a folder that contains the main project and the other functions of the code. However, the data is stored in a folder withing the main one named "data" and inside the specific dataset that i want, for example "ded4" in this example. I can't figure out how to open the text file that I want without changing the file to the main folder. The code I have so far is:
function[Classify] = Classify(logDir)
%%%%logDir='ded014a04';
Directory = ['data/' logDir '/']
Filename = [logDir '-fixationsOffSet']
File_name = fullfile(Directory,Filename)
File = fopen(File_name,'r')
end
The code is in the 'dev' folder, I think my path is correct because when I do
open(File_name)
it opens.
Thanks for the help
If you want to open the file in the editor, use
open(File_name)
If you want to read data from the file, you can use
dlmread(File_name) % Read ASCII delimited file.
or
C = textscan(File,'FORMAT') % Read formatted data from text file or string.
or more low-level using fscanf, e.g., if the file contains three columns of integers you do the following: Read the values in column order, and transpose to match the appearance of the file: (from the help of fprintf)
fid = fopen('count.dat');
A = fscanf(fid,'%d',[3,inf])';
fclose(fid);
I have 1000 text files and want to read a number from each file.
format of text file as:
af;laskjdf;lkasjda123241234123
$sakdfja;lskfj12352135qadsfasfa
falskdfjqwr1351
##alskgja;lksjgklajs23523,
asdfa#####1217653asl123654fjaksj
asdkjf23s#q23asjfklj
asko3
I need to read the number ("1217653") behind "#####" in each txt file.
The number will follow the "#####" closely in all text file.
"#####" and the close following number just appear one time in each file.
clc
clear
MyFolderInfo = dir('yourpath/folder');
fidin = fopen(file_name,'r','n','utf-8');
while ~feof(fidin)
tline=fgetl(fidin);
disp(tline)
end
fclose(fidin);
It is not finish yet. I am stuck with the problem that it can not read after the space line.
This is another approach using the function regex. This will easily provide a more advanced way of reading files and does not require reading the full file in one go. The difference from the already given example is basically that I read the file line-by-line, but since the example use this approach I believe it is worth answering. This will return all occurences of "#####NUMBER"
function test()
h = fopen('myfile.txt');
str = fgetl(h);
k = 1;
while (isempty(str) | str ~= -1 ) % Empty line returns empty string and EOF returns -1
res{k} = regexp(str,'#####\d+','match');
k = k+1;
str = fgetl(h);
end
for k=1:length(res)
disp(res{k});
end
EDIT
Using the expression '#####(\d+)' and the argument 'tokens' instead of 'match' Will actually return the digits after the "#####" as a string. The intent with this post was also, apart from showing another way to read the file, to show how to use regexp with a simple example. Both alternatives can be used with suitable conversion.
Assuming the following:
All files are ASCII files.
The number you are looking to extract is directly following #####.
The number you are looking for is a natural number.
##### followed by a number only occurs once per file.
You can use this code snippet inside a for loop to extract each number:
regx='#####(\d+)';
str=fileread(fileName);
num=str2double(regexp(str,regx,'tokens','once'));
Example of for loop
This code will iterate through ALL files in yourpath/folder and save the numbers into num.
regx='#####(\d+)'; % Create regex
folderDir='yourpath/folder';
files=cellstr(ls(folderDir)); % Find all files in folderDir
files=files(3:end); % remove . and ..
num=zeros(1,length(files)); % Pre allocate
for i=1:length(files) % Iterate through files
str=fileread(fullfile(folderDir,files{i})); % Extract str from file
num(i)=str2double(regexp(str,regx,'tokens','once')); % extract number using regex
end
If you want to extract more ''advanced'' numbers e.g. Integers or Real numbers, or handle several occurrences of #####NUMBER in a file you will need to update your question with a better representation of your text files.
I am reading data from a text file and sort it with matlab. It works well with below script:
load 'con.txt';
A = con;
X = sortrows(A,3);
But I've got many similar text files to sort with different names. E.g. con.txt, bon.txt, ton.txt, etc...
As such, I have to replace the name of file (i.e. load 'filename') to load, and replace matrix (i.e. A='filename') each time when i run the script.
Is there any easier way so that I don't need to replace two lines and A will auto equal to .txt file name?
Thanks.
Maybe something like this:
fname = input('enter filename:', 's');
A = load(fname);
...
So I have a directory that has many .mat files:
apples.mat, oranges.mat, bananas.mat, grapes.mat, apricots.mat, pears.mat, pineapple.mat
All of these .mat files has a variable name "calories" assigned a value. How do I load all of these .mat files simultaneously in MATLAB and change the variables for each one from calories to calories_(fruit name) so that I can have all the variable values in the workspace to play with?
For example, I want to load apples.mat and change its variable name from calories to calories_apple, then load oranges.mat and change is variable name from calories_orange, etc. without doing it all manually.
I know it's something along the lines of creating a string with the different fruit names, and the indexing along the string to load a file and change its variable from variable to variable_%s with the %s indicating the fruit content generated along the loop. It's a big mess for me, however, I don't think I'm structuring it right. Would anyone care to help me out?
I would load each .mat file in sequence and put each of the corresponding calories as a separate field being all combined into a single struct for you to access. Given the directory of where these .mat files appear, do something like this:
%// Declare empty structure
s = struct()
folder = '...'; %// Place directory here
%// Get all MAT files in directory
f = dir(fullfile(folder, '*.mat'));
%// For each MAT file...
for idx = 1 : numel(f)
%// Get absolute path to MAT file - i.e. folder/file.mat
name = fullfile(folder, f(idx).name);
%// Load this MAT file into the workspace and get the calories variable
load(name, 'calories');
%// Get the name of the fruit, are all of the characters except the last 4 (i.e. .mat)
fruit_name = f(idx).name(1:end-4);
%// Place corresponding calories of the fruit in the structure
s.(['calories_' fruit_name]) = calories;
end
You can then access each of the calories like so using dot notation:
c = s.calories_apple;
d = s.calories_orange;
...
...
... and so on.
I am assuming that you do not mean to include the parenthesis in calories_(fruit name). I am also assuming there are no other .mat files in your current directory. This should do the trick:
theFiles = dir('*.mat');
for k = 1:length(theFiles)
load(theFiles(k).name, 'calories');
eval(['calories_' theFiles(k).name(1:length(theFiles(k).name)-4) ' = calories;'])
clear calories
end
Let me know if this helps or not.
EDIT
As, rayryeng points out. The use of eval is, apparently, a bad practice. So, if you are willing to change the way you are thinking about the problem, I suggest you use a structure. In which case, rayryeng's response would be an acceptable answer, even though it does not directly answers your original question.
I need to save multiple arrays to a text file with the filename the same as the variable name. I have created a vector of all the variables required using the follow lines.
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
end
end
I am now struggling to find a way to save all of these variable to file. Any help would be appreciated.
Thank you
I'm not sure if I understood correctly. Do you want to save each variable in different files? Assuming you want to save all variables in the same file with, lets say, the first value of the vector as the filename, you could try something like:
filename = sprintf('vector_starting_with%d.mat', vars(1).name);
save(filename)
In case you want separated files for each element in the vector, you could try:
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
varsave=sprintf('vector_%d.mat', vars(i).name)
save(varsave);
end
end
Sorry that it might have some bugs, right now I don't have MATLAB. Nevertheless, try to go over this documentation.
Edit Let me know if you try this then:
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
filename = sprintf('%d.txt', vars(i).name);
file = fopen(filename,'w');
fprintf(file,vars(i).name);
fclose(file);
end
end