Sequence save of .dat files in matlab - matlab

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.

Related

Check wav file exists in Matlab folder

I need to check whether a wav file in Matlab work folder exists ou not. If it does, I need to load the file into a variable (file in my case), i use this code but it doesn't work.
if strcmp(file,'\n')==0
file='test.wav';
elseif findstr(file,'.')==''
file=strcat(file,'.wav');
end
[TestWave,Fs] = audioread(file);
You don't say if you are trying to find a particular .WAV file, or just any .WAV file...
If you just want to know if a particular file (of any kind) exists, use the exist() function. It returns value 2 if a file exits:
myFileName = 'test.wav';
myDirectory = 'c:\temp';
filepath = fullfile(myFileName,myDirectory);
if exist(filepath,'file') == 2
[TestWave,Fs] = audioread(file);
end
Otherwise, just search for the files you need using dir():
myDirectory = 'c:\temp';
wildcard = '*.wav';
theseFiles = dir(fullfile(myDirectory,wildcard));
for i = 1:length(theseFiles)
thisFilePath = fullfile(myDirectory,theseFiles(i).name);
[TestWave,Fs] = audioread(thisFilePath); % Load this file
% Do something with the loaded file...
end

Extract value MATLAB

I need to extract the first value of the following code:
3.43099,70.8539,91.701,FAIL
The file has the '.sol' extension, but it can be read in notepad or Matlab.
I just want to know how to to read in all *.sol files in a folder and how to write the extracted value in a text file.
Thanks a lot, i would be grateful.
NEW
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
Many thanks
File extension does not make a difference as to what MATLAB can "read", use the fileread command to load in the file and parse its contents. You can then split on commas, since it looks like it is comma separated
files = dir('*.sol');
fh = fopen('outFile.txt','w');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
parts = regexp(contents,',','Split');
fprintf(fh,[parts{1},'\n']);
end
end
fclose(fh)
This should do what you want. It will find all files in the current directory with the .sol extension, loop through all of them, grab the first value, and write it out to a text file.
Find and replace
Finding and replacing is relatively simple as well. You can do the same looping, read the file contents, run a replacement, and then rewrite that out to the same file.
files = dir('*.sol');
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'); % open handle to same file just read for overwriting
contents = regexprep(contents,'toReplace','replacement'); % do string replacement
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end

Save data as modified input file name

I have a program that loads data from a .txt file and performs some curve fitting. The input file name for this example is experiment09.txt.
After processing I want to save a variable with the same input filename but appended with something like _fit. So my saved workspace variable in this case would be experiment09_fit.txt.
I have gotten this far in MATLAB:
buf = length(filename)
saveName = filename(1:buf-7)
which gives me a saveName of experiment09 but I am at a loss as to how to add my chosen string on the end to make it experiment09_fit. Once I have a valid save name I will then just call
save(saveName, 'fittedValue', '-ASCII');
Help would be greatly appreciated.
What about this:
filename = 'experiment09.txt';
[pathstr, basename, ext] = fileparts(filename);
outname = [basename, '_fit', ext]; % will give 'experiment09_fit.txt'
Also use string concatenation for adding additional names to string variables.
For example,
filename = 'experiment09.txt';
[pathstr, name, ext] = fileparts(filename);
outputName1 = strcat(name,'_fit.');
outputName = strcat(outputName1,ext);

Saving file with part of file name and date

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!

What do I have to add at the beginning of this loop?

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