Taking symbolic variables out of txt file and making a matrix in Matlab - matlab

I have a txt file containing following characters.
theta1 , l1 and others are symbolic variables.( Don't mind about it)
M=[theta1 + (l1^2*m1)/4 + l1^2*m2 (l1*l2*m2*cos(fi1 - fi2))/2 ;
(l1*l2*m2*cos(fi1 - fi2))/2 theta2 + (l2^2*m2)/4 ]
I need to take it out and make it a symbolic matrix. As you can see txt file is already fine for making matrix but I don't want to copy paste the whole thing to script, I rather want to do it automatically.
fid = fopen('a.txt');
MMatrix=textscan(fid,'%s');
fclose(fid);
I tried the code above but it turn out to be not useful. What do you think is the way to copy the whole thing and use it for matrix making?

Instead of reading that as a string or a character array and then possibly resorting to evil (eval) method, just rename the extension from txt to m since you already have your arrays defined in the MATLAB way in the text files. Maintain a backup copy of those original txt files if needed.
If it is a single file (a.txt), you can rename it manually or with this code to a.m:
movefile('a.txt', 'a.m');
If there are multiple such files in a directory then you can use the following code to change the extension of all such txt files in the current directory:
txtfiles = dir('*.txt'); %getting all txt files in the current directory
for num = 1:numel(txtfiles)
[~, fname] = fileparts(txtfiles(num).name); %filename (without extension)
movefile(txtfiles(num).name, [fname,'.m']); %renaming
end
Now you can simply use the name of the respective file in your script to get whatever arrays that file have in it.

Related

Loop through .fig files and group them into folders based on the file name

I have a lot of .fig files that are named like this: 20160922_01_id_32509055.fig, 20160921_02_id_53109418.fig and so on.
So I thought that I create a script that loop through all the .fig files in the folder and group(copy) them into another folder(s) based on the last number in the file name. The folder is created based on the id number. Is this possible?
I have been looking on other solutions involving looping through folders but I am totally fresh. This would make it easier for me to check the .fig files while I am learning to do other stuff in Matlab.
All is possible with MATLAB! We can use dir to get all .fig files, then use regexp to get the numeric part of each filename and then use copyfile to copy the file to it's new home. If you want to move it instead, you can use movefile instead .
% Define where the files are now and where you want them.
srcdir = '/my/input/directory';
outdir = '/my/output/directory';
% Find all .fig files in the source directory
figfiles = dir(fullfile(srcdir, '*.fig'));
figfiles = {figfiles.name};
for k = 1:numel(figfiles)
% Extract the last numeric part from the filename
numpart = regexp(figfiles{k}, '(?<=id_)\d+', 'match', 'once');
% Determine the folder we are going to put it in
destination = fullfile(outdir, numpart);
% Make sure the folder exists
if ~exist(destination, 'dir')
mkdir(destination)
end
% Copy the file there!
copyfile(fullfile(srcdir, figfiles{k}), destination)
end
Here's an example how to identify and copy the files. I'll let you do the for loop :)
>> Figs = dir('*.fig'); % I had two .fig files on my desktop
>> Basename = strsplit(Figs(1).name, '.');
>> Id = strsplit(Basename{1}, '_');
>> Id = Id{3};
>> mkdir(fullfile('./',Id));
>> copyfile(Figs(1).name, fullfile('./',Id));
Play with the commands to see what they do. It should be straightforward :)

Matlab:renaming Files in a Sequential Order

I have a number of text files with no Sequential Order :
010010.txt 010030.txt 010070.txt
How could I change the file names to:
text01.txt text02.txt ....
Is it possible not to re writte over the old directory but create a new directory
I have used the following script but the result is that it is working fine but it goes from text001.txt to text021.txt to then text041.txt
any idea?
directory = 'C:\test\'; %//' Directory with txt files
filePattern = fullfile(directory, '*.txt'); %//' files pattern with absolute paths
old_filename = cellstr(ls(filePattern)) %// Get the filenames
file_ID = strrep(strrep(old_filename,'file',''),'.txt','') %// Get numbers associated with each file
file_ID_doublearr = str2double(file_ID)
file_ID_doublearr = file_ID_doublearr - min(file_ID_doublearr)+1
file_ID = strtrim(cellstr(num2str(file_ID_doublearr)))
str_zeros = arrayfun(#(t) repmat('0',1,t), 4-cellfun(#numel,file_ID),'uni',0) %// Get zeros string to be pre-appended to each filename
new_filename = strcat('file',str_zeros,file_ID,'.txt') %// Generate new filenames
cellfun(#(m1,m2) movefile(m1,m2),fullfile(directory,old_filename),fullfile(directory,new_filename)) %// Finally rename files with the absolute paths
That looks pretty complicated. I would simply make a system call to move all of the files to a new directory, then sequentially rename each file one at a time with additional system calls. It also looks like you're using Windows, so I'll provide a solution for that platform. You have the beginning right where you are reading in the files from a source directory.
directory = 'C:\test\'; %// Directory with txt files
directoryToCopyOver = 'C:\out\'; %// Directory where you want to copy the files over
%// Copy source directory to target directory
system(['xcopy ' directory ' ' directoryToCopyOver]);
filePattern = fullfile(directoryToCopyOver, '*.txt'); %//' files pattern with absolute paths
names = dir(filePattern); %// Find all files with above pattern
%// For each file we have...
for idx = 1 : numel(names)
name = names(idx).name; %// Get a name of a file
%// Rename this file to textxx.txt
outName = sprintf('text%2.2d.txt', idx);
%// Call system and rename the file
system(['ren ' directoryToCopyOver name ' ' directoryToCopyOver outName]);
end
Some important things to note is that I use system to make system calls to your Windows command prompt. I use xcopy to copy a whole directory from one point to another. In this case, this would be your source directory over to a new target directory. After I do this, I invoke MATLAB's dir to determine all of the file names that match the particular pattern you have laid out, which is all of the text files.
Then, for each text file name we have, we read in this name, then create an output name of type textxx.txt, where xx is a number starting from 1 to as many text files as we have, and then I invoke the Windows command prompt command ren to rename the file from the original name to the new name. Also, take a look at sprintf from MATLAB. It is designed to create strings using formatting delimiters. If you see how I called it, %2.2d means that I am expecting the number to be two digits long, and should the number be less than two digits, fill the spaces with a zero. If you want to increase the amount of digits, simply add more to each place. For example, if you want to have 4 digits, do %4.4d, and so on. This will properly create the right string so that we can rename the right file in this new directory.
Hope this helps!

MATLAB: Use a variable with a file extenstion to load files

I am using MATLAB
I Have 51 files in their own directory all of .out extention created by a seperate program, all numbered 0 to 50.
ie
0.out
1.out
2.out
and so on til 50.out.
I need to load each file 1 by one to do calculations upon them within a for loop. How would I do this using the count variable to load the file, if the directory is set beforehand?
i.e.
%set directiory
cd(......)
%for loop
For count = 0:50,
data = count.out *<-----this line*
.....
Many thanks!
First generate the file name with
fileName = [int2str(count) '.out'];
then open the file with
fid = fopen(fileName, 'r');
The loading phase depends on the kind of file you want to read. Assuming it is a text file you can, for example, read it line after line with
while ~feof(fid)
line = fgetl(fid);
end
or use more specialized functions (see http://www.mathworks.it/it/help/matlab/text-files.html). Before the end of the for loop you'll have to close the file by calling
fclose(fid);
Another quite nice way to do it is to use the dir function
http://www.mathworks.co.uk/help/matlab/ref/dir.html
a = dir('c:\docs*.out')
Will give you a structure containing all the info about the *.out files in the directory you point it to, (or the path). You can then loop through it bit by bit. using fopen or csvread or whatever file reading function you want to use.

Find and replace text file Matlab

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);

importing excel into matlab

I have 4 folders in the same directory where each folder contains ~19 .xls files. I have written the code below to obtain the name of each of the folders and the name of each .xls file within the folders.
path='E:\Practice';
folder = path;
dirListing = dir(folder);
dirListing=dirListing(3:end);%first 2 are just pointers
for i=1:length(dirListing);
f{i} = fullfile(path, dirListing(i,1).name);%obtain the name of each folder
files{i}=dir(fullfile(f{i},'*.xls'));%find the .xls files
for j=1:length(files{1,i});
File_Name{1,i}{j,1}=files{1,i}(j,1).name;%find the name of each .xls file
end
end
Now I'm trying to import the data from excel into matlab by using xlsread. What I'm struggling with is knowing how to load the data into matlab within a loop where the excel files are in different directories (different folders).
This leaves me with a 1x4 cell named File_Name where each cell refers to a different folder located under 'path', and within each cell is then the name of the spreadsheets wanting to be imported. The size of the cells vary as the number of spreadsheets in each folder varies.
Any ideas?
thanks in advance
I'm not sure if I'm understanding your problem, but all you have to do is concatenate the strings that contain directory (f{}) and the file name. Modifying your code:
for i=1:length(dirListing);
f{i} = fullfile(path, dirListing(i,1).name);%obtain the name of each folder
files{i}=dir(fullfile(f{i},'*.xls'));%find the .xls files
for j=1:length(files{1,i});
File_Name{1,i}{j,1}=files{1,i}(j,1).name;%find the name of each .xls file
fullpath = [f{i} '/' File_Name{1,i}{j,1}];
disp(['Reading file: ' fullpath])
x = xlsread(fullpath);
end
end
This works on *nix systems. You may have to join the filenames with a '\' on Windows. I'll find a more elegant way and update this posting.
Edit: The command filesep gives the forward or backward slash, depending on your system. The following should give you the full path:
fullpath = [f{i} filesep File_Name{1,i}{j,1}];
Take a look at this helper function, written by a member of the matlab community.
It allows you to recursively search through directories to find files that match a certain pattern. This is a super handy function to use when looking to match files.
You should be able to find all your files in a single call to this function. Then you can loop through the results of the rdir function, loading the files one at a time into whatever data structure you want.