I am using MATLAB to process data from files. I am writing a program that takes input from the user and then locates the particular files in the directory graphing them. Files are named:
{name}U{rate}
{name} is a string representing the name of the computer. {rate} is a number. Here is my code:
%# get user to input name and rate
NET_NAME = input('Enter the NET_NAME of the files: ', 's');
rate = input('Enter the rate of the files: ');
U = strcat(NET_NAME, 'U', rate)
load U;
Ux = U(:,1);
Uy = U(:,2);
There are currently two problems:
When I do the strcat with say 'hello', 'U', and rate is 50, U will store 'helloU2' - how can I get strcat to append {rate} properly?
The load line - how do I dereference U so load tries to load the string stored in U?
Many thanks!
Mikhail's comment above solves your immediate problem.
A more user-friendly way of selecting a file:
[fileName,filePath] = uigetfile('*', 'Select data file', '.');
if filePath==0, error('None selected!'); end
U = load( fullfile(filePath,fileName) );
In addition to using SPRINTF like Mikhail suggested, you can also combine strings and numeric values by first converting the numeric values to strings using functions like NUM2STR and INT2STR:
U = [NET_NAME 'U' int2str(rate)];
data = load(U); %# Loads a .mat file with the name in U
One issue with the string in U is that the file has to be on the MATLAB path or in the current directory. Otherwise, the variable NET_NAME has to contain a full or partial path like this:
NET_NAME = 'C:\My Documents\MATLAB\name'; %# A complete path
NET_NAME = 'data\name'; %# data is a folder in the current directory
Amro's suggestion of using UIGETFILE is ideal because it helps you to ensure you have a complete and correct path to the file.
Related
I have a text file that is a Fortran code. I am trying to create copies (Fortran files) of this code. But in each copy I create I want to find and replace few things. As an example:
This is the code and I want to search for pMax, tShot, and replace the numbers next to it.
I would be grateful if someone can give me a hint on how this can be done using python 3.x. Thank you.
This is my try at it:
There is no error but for some reason, re.sub() doesn't replace the string with the desired string 'pMax' in the destination file. Although printing the return value of re.sub shows that the pMax is modified to the desired value.
vd_load_name = []
for i in range(len(Pressure_values)):
vd_load_name.append('{}_{}MPa'.format(n,int(Pressure_values[i])))
src_dir = os.getcwd() #get the current working dir
# create a dir where we want to copy and rename
dest_dir = os.mkdir('vd_loads')
os.listdir()
dest_dir = src_dir+"/vd_loads"
for i in range(len(vd_load_name)):
src_file = os.path.join(src_dir, 'n_t05_pressure_MPa.txt')
shutil.copy(src_file,dest_dir) #copy the file to destination dir
dst_file = os.path.join(dest_dir,'n_t05_pressure_MPa.txt')
new_dst_file_name = os.path.join(dest_dir, vd_load_name[i]+'.txt')
os.rename(dst_file, new_dst_file_name)#rename
os.chdir(dest_dir)
dest_file_path = dest_dir+'/'+vd_load_name[i]+'.txt'
with open(dest_file_path,'r+') as reader:
#reading all the lines in the file one by one
for line in reader:
re.sub(r"pMax=\d+", "pMax=" + str(int(Pressure_values[i])), line)
print(re.sub(r"pMax=\d+", "pMax=" + str(int(Pressure_values[i])), line))
Actualy part of the fortran code that I want to edit:
integer :: i !shot index in x
integer :: j !shot index in y
integer :: sigma !1D overlap
dimension curCoords(nblock,ndim), velocity(nblock,ndim),dirCos(nblock,ndim,ndim), value(nblock)
character*80 sname
pMax=3900d0 !pressure maximum [MPa] Needs to be updated!!
fact=1d0 !correction factor
JLTYP=0 !key that identifies the distributed load type, 0 for Surface-based load
t=stepTime !current time[s]
tShot=1.2d-7 !Time of a shot[s] Needs to be updated!!
sigma=0 !1D overlap in x&y [%]
I am writing data to a notepad (.txt) file in Python. Entities are separated with commas (','). The file is called 'Database2.txt'.
The variable 'yearlynew' contains a float value that will replace a piece of existing data. I have tried various methods of writing said data to the file but cannot get it to work.
This is the code that I have so far:
g = open('Database2.txt', 'r')
for line in g:
CurrentLine = line.split(',')
if CurrentLine[0] == account:
g = open('Database2.txt', 'a')
#CurrentLine[3] = yearlynew
#g(CurrentLine[3]).write(yearlynew)
#CurrentLine[3].write(yearlynew)
Anything with a '#' before it indicates a failed method that I have tried. If anybody has any suggestions on how to do this I would be very grateful.
I should note that CurrentLine[0] identifies usernames (which are in the first column of the file) so that whichever user is logged in can edit their data and their data only. 'account' holds the username of the user that is currently logged in, and allows the program to trace through the file to find the user's statistics. User data such as names and passwords are stored in a separate file and are not needed for this function.
This is the contents of the file:
Ellie121,0.16,5,60,
Sam232,0.2,6,72,
Heather343,0.1,3,36,
Connor454,0.35,10.5,126,
Ryan565,0.15,4.5,54,
Matthew676,0.22,6.6,79.2,
I don’t think that you can just insert text into a file. I think you will have to write the new data to a different file and then rename it. This is how I would go about it :
import os
account = 'Sam232'
yearlynew = '3.14159'
temp = open ('temporary_file', 'w')
g = open ('Database2.txt', 'r')
for line in g :
CurrentLine = line.split (',')
if CurrentLine [0] == account :
CurrentLine [1] = yearlynew
OutputLine = ','.join (CurrentLine)
temp.write (OutputLine)
g.close ()
temp.close ()
os.remove ('Database2.txt')
os.rename ('temporary_file', 'Database2.txt')
I want create a string variable using ´sprintf´ and a random name from a list (in order to save an image with such a name). A draft of the code is the following:
Names = [{'C'} {'CL'} {'SCL'} {'A'}];
nameroulette = ceil(rand(1)*4)
filename = sprintf('DG_%d.png', Names{1,nameroulette});
But when I check filename, what I get is the text I typed followed not by one of the strings, but by a number that I have no idea where it comes from. For example, if my nameroulette = 1 then filename is DG_67.png, and if nameroulette = 4, filename = 'DG_65.png' . Where does this number come from and how can I fix this problem?
You just need to change
filename = sprintf('DG_%d.png', Names{1,nameroulette});
to
filename = sprintf('DG_%s.png', Names{1,nameroulette});
By the way you may want to have a look at randi command for drawing random integers.
I have a simple script to import some spectroscopy data from files with some base filename (YYYYMMDD) and a header. My current method pushes the actual spectral intensities to some vector 'rawspectra' and I can call the data by `rawspectra{m,n}.data(q,r)
In the script, I specify by hand the base filename and save it as a string 'filebase'.
I would like to append the name of the rawspectra vector with the filebase so I might be able to use the script to import files acquired on different dates into the same workspace without overwriting the rawspectra vector (and also allowing for easy understanding of which vectors are attached to which experimental conditions. I can easily do this by manually renaming a vector, but I'd rather make this automatic.
My importation script follows:
%for the importation of multiple sequential files, starting at startfile
%and ending at numfiles. All raw scans are subsequently plotted.
numfiles = input('How many spectra?');
startfile = input('What is the starting file number?');
numberspectra = numfiles - (startfile - 1);
filebase = strcat(num2str(input('what is the base file number?')),'_');
rawspectra = cell(startfile, numberspectra);
for k= startfile:numberspectra
filename = strcat(filebase,sprintf('%.3d.txt', k));
%eval(strcat(filebase,'rawspectra')){k} = importdata(filename); - This does not work.
rawspectra{k} = importdata(filename);
figure;
plot(rawspectra{1,k}.data(:,1),rawspectra{1,k}.data(:,2))
end
If any of you can help me out with what should be a seemingly simple task, I would be very appreciative. Basically, I want 'filebase' to go in front of 'rawspectra' and then increment that by k++ within the loop.
Thanks!
Why not just
rawspectra(k) = importdata(filename);
rawspectra(k).filebase = filebase;
I want to use a for loop to export the names of a folder of .mat files into one .csv file by row.
I am trying to use xlswrite, but don't understand how to access the filename of the .mat files.
I am working with to write them to the csv.
xlswrite(fullfile(dest_dir,'result.csv'), FILENAME HERE, ['A' num2str(i)]);
xlswrite creates a excel workbook
With dir command you can get a structure whose one of field is name of file.
Using simple file IO function your requirement can be met.
I think either of this will do what you need:
fid=fopen('result.csv','wt');
files=dir('*.mat');
x={files(:).name};
csvFun = #(str)sprintf('%s,',str);
xchar = cellfun(csvFun, x,'UniformOutput', false);
xchar = strcat(xchar{:});
xchar = strcat(xchar(1:end-1),'\n');
fprintf(fid,xchar);
fclose(fid);
Or
If you just need .mat names in a column form:
fid=fopen('result.csv','wt');
files=dir('*.mat');
x={files(:).name};
[rows,cols]=size(x);
for i=1:rows
fprintf(fid,'%s,',x{i,1:end-1});
fprintf(fid,'%s\n',x{i,end});
end
fclose(fid);
To get your filename, load the files using dir command, read them individually in your for loop, and then write them to file. (I think I already posted something like this?) Here is the prototype:
files = dir('*.mat'); % obtain all files with .mat extenstion
fid = fopen('result.csv','a');
for k = 1:length(data)
filename = files(k).name; % get the filename
fprintf(fid, '%s,\n', filename);
end
fid = fclose(fid);
Unfortunately, you cannot just save the file names as strings in a cell and write it as you might a matrix using say csvwrite, so you can just do this.