Hi there I'm currently trying to find a way to save 2 variables from my workspace into a file. I want the file name to be put together using the original and the current date.
I only want the max value from the variables so:
max(streaking)
and
max(tap_total)
The original file name is:
3_FM001_02_05460$BandP$64_24000_FWD_1x1_PRI_PRI_PRI_PRI_15_17_ActivePixelMeans.csv
The only portion of this original file name that I would like to use is:
3_FM001_02_05460$BandP$64_24000_FWD_1x1
These can be saved in a text file or spreadsheet, it doesnt matter.
An example of the new file name would be something like this:
3_FM001_02_05460$BandP$64_24000_FWD_1x1_7-26-2012
Also,
If something could be done in the file to display which variable is which, for example:
Streaking: 1.272 % this would come from the variable max(streaking)
Tap_Total: 2.252 % this would come from the varaible max(tap_total)
EDIT:
% Construct a questdlg with three options
choice = questdlg('Would you like to save?', ...
'Save Options', ...
'Yes','No','Cancel','Cancel');
% Handle response
switch choice
case 'Yes'
disp([choice ' processing.'])
save_option = 1;
case 'No'
disp([choice ' processing.'])
save_option = 0;
case 'Cancel'
disp('Canceled.')
save_option = 2;
end
file_to_get = evalin( 'base', 'file_to_get' );
streaking = evalin( 'base', 'streaking' );
tap_total = evalin( 'base', 'tap_total' );
if save_option == 0
elseif save_option == 1
max_streak = max(streaking);
max_tap = max(tap_total);
str_streak = mat2str(max_streak);
str_tap = mat2str(max_tap);
fname = file_to_get;
pruned_fname = regexprep(fname,'_PRI(\w*).(\w*)','');
new_fname = [pruned_fname '_' date '.csv'];
path1 = '\\pfile01thn\bbruffey$\My Documents\analysis data\Banding and Streaking Results';
fid = fopen([path1 new_fname], 'w');
fprintf(fid,['Max Banding: %s\nMax Streaking: %s'],str_tap,str_streak)
fclose(fid);
elseif save_option == 2
end
This would be a great place to use the regexprep command to prune the original filename down.
Example:
fname = '3_FM001_02_05460$BandP$64_24000_FWD_1x1_PRI_PRI_PRI_PRI_15_17_ActivePixelMeans.csv';
pruned_fname = regexprep(fname,'_PRI(\w*).(\w*)','');
pruned_fname =
3_FM001_02_05460$BandP$64_24000_FWD_1x1
Now, a note about the regexprep command I used here. This is specific for the filename you provided here. Since it looks like you want to trim off everything after the the first _PRI I used a tag (\w*) which means any combination of [a-z A-Z _ 0-9] can follow. Notice that since this is a filename there is a . there hence why I added a period in and followed that with another (\w*) to finish out the csv. You can find more info on these sorts of operators here.
Now that you have the pruned_fname you can simply add whatever you want to it. So if you want to add the date in with an underscore to space it just simply do something like this:
new_fname = [pruned_fname '_' date '.csv'];
new_fname =
3_FM001_02_05460$BandP$64_24000_FWD_1x1csv_26-Jul-2012.csv
Now you simply need to open the file to write to it. you might need to append the path to where you want to save it, I'm just going to call it path for now. It would be something like C:\Documents\
fid = fopen([path new_fname], 'w')
Now with the fid you have the id of the file you want to write to. This should be a new file and if it isn't you are going to overwrite the file contents if you do it this way. Just be aware =)
Next you can simply write those first two lines to the file using fwrite fprintf, just to name a few possible functions.
Hopefully that'll get you setup there!
Related
I want to loop over a cell array while reading in files within a working
folder. If that file exists, create and open new file called testcase.txt
print statement. If that file doesn't exist in working folder, do nothing
and move on to next iteration.
Here's what example looks like with search for one file
fid=fopen('testcase.txt','w');
if exists('abc.txt','file')
abc.txt = 1;
fprintf('test case successful');
else
abc.txt = 0;
end
fclose(fid);
Here's a cell array example expanded over multiple cases looks like
I can't seem to get it to run properly. Can someone help me to get this
loop to work?
extension = {'abc.txt' 'def.txt' 'ght.txt'};
convertedfile = [abc.txt def.txt ght.txt];
fid=fopen('testcase.txt','w');
for i = extension
if exist(['''' convertedfile ''''],'file')
i = 1;
fprintf('test case successful');
else
i = 0;
end
end
fclose(fid);
Are you looking for something like this?
extension = {'abc.txt' 'def.txt' 'ght.txt'};
% convertedfile = [abc.txt def.txt ght.txt];
fid=fopen('testcase.txt','w');
for i = 1:length(extension)
if ~exist(extension{i},'file')
fprintf(fid,'test case successful\n');
end
end
fclose(fid);
Also, you could print the text file for which it was successful using:
fprintf(fid,'%s: test case successful\n',extension{i});
this question about matlab:
i'm running a loop and each iteration a new set of data is produced, and I want it to be saved in a new file each time. I also overwrite old files by changing the name. Looks like this:
name_each_iter = strrep(some_source,'.string.mat','string_new.(j).mat')
and what I#m struggling here is the iteration so that I obtain files:
...string_new.1.mat
...string_new.2.mat
etc.
I was trying with various combination of () [] {} as well as 'string_new.'j'.mat' (which gave syntax error)
How can it be done?
Strings are just vectors of characters. So if you want to iteratively create filenames here's an example of how you would do it:
for j = 1:10,
filename = ['string_new.' num2str(j) '.mat'];
disp(filename)
end
The above code will create the following output:
string_new.1.mat
string_new.2.mat
string_new.3.mat
string_new.4.mat
string_new.5.mat
string_new.6.mat
string_new.7.mat
string_new.8.mat
string_new.9.mat
string_new.10.mat
You could also generate all file names in advance using NUM2STR:
>> filenames = cellstr(num2str((1:10)','string_new.%02d.mat'))
filenames =
'string_new.01.mat'
'string_new.02.mat'
'string_new.03.mat'
'string_new.04.mat'
'string_new.05.mat'
'string_new.06.mat'
'string_new.07.mat'
'string_new.08.mat'
'string_new.09.mat'
'string_new.10.mat'
Now access the cell array contents as filenames{i} in each iteration
sprintf is very useful for this:
for ii=5:12
filename = sprintf('data_%02d.mat',ii)
end
this assigns the following strings to filename:
data_05.mat
data_06.mat
data_07.mat
data_08.mat
data_09.mat
data_10.mat
data_11.mat
data_12.mat
notice the zero padding. sprintf in general is useful if you want parameterized formatted strings.
For creating a name based of an already existing file, you can use regexp to detect the '_new.(number).mat' and change the string depending on what regexp finds:
original_filename = 'data.string.mat';
im = regexp(original_filename,'_new.\d+.mat')
if isempty(im) % original file, no _new.(j) detected
newname = [original_filename(1:end-4) '_new.1.mat'];
else
num = str2double(original_filename(im(end)+5:end-4));
newname = sprintf('%s_new.%d.mat',original_filename(1:im(end)-1),num+1);
end
This does exactly that, and produces:
data.string_new.1.mat
data.string_new.2.mat
data.string_new.3.mat
...
data.string_new.9.mat
data.string_new.10.mat
data.string_new.11.mat
when iterating the above function, starting with 'data.string.mat'
I try to save the each step results into sequence format. i.e.
cm_clusters_2_00001.dat
cm_clusters_2_00002.dat
cm_clusters_2_00003.dat
.
.
.
cm_clusters_2_00020.dat
"particles_file_name" show me the required file name in correct format but when it save that file it write "particles_file_name" and that is why i am over writing my results under the same name.
Part of code which generate sequence names:
for kk= 1:20
if(kk<10)
file_number = ['0000' int2str(kk)];
elseif(kk>=10 && kk<100)
file_number = ['000' int2str(kk)];
elseif(kk>=100 && kk<1000)
file_number = ['00' int2str(kk)];
elseif(kk>=1000 && kk<10000)
file_number = ['0' int2str(kk)];
end
particles_file_name = ['cm_clusters_2_' file_number '.dat'];
save ('particles_file_name')
end;
any body suggest me the the correct way how to save these file so its not over written under the same name. As code show the correct name
particles_file_name = ['cm_clusters_2_' file_number '.dat'];
but Save it wrong.
You need to change:
save('particles_file_name')
to
save(particles_file_name)
particles_file_name is your variable with the changing file name, so you need to pass it directly to the save command. What you are doing instead is passing a string 'particles_file_name' which has no relation whatsoever with the variable particles_file_name.
I am really just a noob at Matlab, so please don't get upset if I use wrong syntax. I am currently writing a small program in which I put all .xlsx file names from a certain directory into an array. I now want to separate the files into two different arrays based on their name. This is what I tried:
files = dir('My_directory\*.xlsx')
file_number = 1;
file_amount = length(files);
while file_number <= file_amount;
file_name = files(file_number).name;
filescs = [];
filescwf = [];
if strcmp(file_name,'*cs.xlsx') == 1;
filescs = [filescs,file_name];
else
filescwf = [filescwf,file_name];
end
file_number = file_number + 1
end
The idea here is that strcmp(file_name,'*cs.xlsx') checks if file_name contains 'cs' at the end. If it does, it is put into filescs, if it doesn't it is put into filescwf. However, this does not seem to work...
Any thoughts?
strcmp(file_name,'*cs.xlsx') checks whether file_name is identical to *cs.xlsx. If there is no file by that name (hint: few file systems allow '*' as part of a file name), it will always be false. (btw: there is no need for the '==1' comparison or the semicolon on the respective line)
You can use array indexing here to extract the relevant part of the filename you want to compare. file_name(1:5), will give you the first 5 characters, file_name(end-5:end) will give you the last 6, for example.
strcmp doesn't work with wildcards such as *cs.xlsx. See this question for an alternative approach.
You can use regexp to check the final letters of each of your files, then cellfun to apply regexp to all your filenames.
Here, getIndex will have 1's for all the files ending with cs.xlsx. The (?=$) part make sure that cs.xlsx is at the end.
files = dir('*.xlsx')
filenames = {files.name}'; %get filenames
getIndex = cellfun(#isempty,regexp(filenames, 'cs.xlsx(?=$)'));
list1 = filenames(getIndex);
list2 = filenames(~getIndex);
how I can read the following files using the for loop: (can the loop ignore the characters in filenames?)
abc-1.TXT
cde-2.TXT
ser-3.TXT
wsz-4.TXT
aqz-5.TXT
iop-6.TXT
What do I have to add at the beginning of this loop ??
for i = 1:1:6
nom_fichier = strcat(['MyFile\.......' num2str(i) '.TXT']);
You can avoid constructing the filenames by using the DIR command. For instance:
myfiles = dir('*.txt');
for i = 1:length(myfiles)
nom_fichier = myfiles(i).name;
...do processing here...
end
First of all, why would you use strcat here? This is, by itself, a SINGLE string. All concatenation has already been done by the brackets [].
['MyFile\.......' num2str(i) '.TXT']
Next, I'm not certain what is your question here. Is it how to load in the data? If the files are simply delimited numbers, with the same number of them on each line, then load will suffice to load them in, or perhaps you may need textread.
My guess is you do not know how to build the main part of of the file name. You might do it this way:
Names = {'abc' 'cde 'ser' 'wsz' 'aqz' 'iop'};
for i = 1:6
fn = ['MyFile',filesep,Names{i},'-',num2str(i),'.TXT'];
data = load(fn);
% do other stuff ...
end
If you don't want to create a variable with the names by typing them in, then use dir, perhaps like this to create a list of text file names:
Names = dir('MyFile\*.TXT');