matlab How to remove .jpg from file name - matlab

I am looping through a lot of files and I need to remove the '.jpg' from each name.
Example file name:
20403y.jpg
but I just need the
20403y
All the file names end with 'y' if that helps.

One way is with regular expressions:
filename = 'myfilename.jpg';
pattern = '.jpg';
replacement = '';
regexprep(filename,pattern,replacement)
Result:
ans =
myfilename
If you have the filenames in a cell array feed the cell array to regexprep. As the documentation explains, "If str is a cell array of strings, then the regexprep return value s is always a cell array of strings having the same dimensions as str."
Example:
myfilenames = {'myfilename.jpg' 'afilename.jpg' 'anotherfilename.jpg' };
newfilenames= regexprep(myfilenames,'.jpg','');
Result:
newfilenames =
'myfilename' 'afilename' 'anotherfilename'

files = dir('*y.jpg');
% Loop through each
for id = 1:length(files)
% Get the file name (minus the extension)
[p, f] = fileparts(files(id).name); % f will just give you file name
% Use following to rename the files
% I think you don't want to rename them
% movefile(files(id).name, f);
end

Related

iterating only through the files names in a directory using MATLAB

How to only access the file names in a directory?
>> files = dir('*.png');
>> disp(class(dir('*.png')))
struct
>> fields
fields =
'name'
'date'
'bytes'
'isdir'
'datenum'
>> for i=1:numel(fields)
files.(fields{i}.name)
end
Struct contents reference from a non-struct array object.
>> for i=1:numel(fields)
files.(fields{i}).name
end
Expected one output from a curly brace or dot indexing expression, but there were 11 results.
File names are in the field names of the struct array returned by dir. So:
files = dir('*.png');
for k = 1:numel(files)
f = files(k).name; % f contains the name of each file
end
You can use ls like this
list=ls('*.png');
for ii=1:size(list,1)
s = strtrim(list(ii,:)); % a string containing the name of each file
end
ls works with chars instead of cells.

Matlab | How to load/use files with consecutive names (abc1, abc2, abc3) and then pass on to the next series (cba1, cba2, cba3)?

I have a folder containing a series of data with file names like this:
abc1
abc2
abc3
bca1
bca2
bca3
bca4
bca5
cba1
... etc
My goal is to load all the relevant files for each file name, so all the "abc" files, and plot them in one graph. Then move on to the next file name, and do the same, and so forth. Is there a way to do this?
This is what I currently have to load and run through all the files, grab the data in them and get their name (without the .mat extension) to be able to save the graph with the same filename.
dirName = 'C:\DataDirectory';
files = dir( fullfile(dirName,'*.mat') );
files = {files.name}';
data = cell(numel(files),1);
for i=1:numel(files)
fname = fullfile(dirName,files{i});
disp(fname);
files{i} = files{i}(1:length(files{i})-4);
disp(files{i});
[Rest of script]
end
You already found out about the cool features of dir, and have a cell array files, which contains all file names, e.g.
files =
'37abc1.mat'
'37abc2.mat'
'50bca1.mat'
'50bca2.mat'
'1cba1.mat'
'1cba2.mat'
The main task now is to find all prefixes, 37abc, 50bca, 1cba, ... which are present in files. This can be done using a regular expression (regexp). The Regexp Pattern can look like this:
'([\d]*[\D]*)[\d]*.mat'
i.e. take any number of numbers ([\d]*), then any number of non-numeric characters ([\D]*) and keep those (by putting that in brackets). Next, there will be any number of numeric characters ([\d]*), followed by the text .mat.
We call the regexp function with that pattern:
pre = regexp(files,'([\d]*[\D]*)[\d]*.mat','tokens');
resulting in a cell array (one cell for each entry in files), where each cell contains another cell array with the prefix of that file. To convert this to a simple not-nested cell array, we call
pre = [pre{:}];
pre = [pre{:}];
resulting in
pre =
'37abc' '37abc' '50bca' '50bca' '1cba' '1cba'
To remove duplicate entries, we use the unique function:
pre = unique(pre);
pre =
'37abc' '50bca' '1cba'
which leaves us with all prefixes, that are present. Now you can loop through each of these prefixes and apply your stuff. Everything put together is:
% Find all files
dirName = 'C:\DataDirectory';
files = dir( fullfile(dirName,'*.mat') );
files = {files.name}';
% Find unique prefixes
pre = regexp(files,'([\d]*[\D]*)[\d]*.mat','tokens');
pre = [pre{:}]; pre = [pre{:}];
pre = unique(pre);
% Loop through prefixes
for ii=1:numel(pre)
% Get files with this prefix
curFiles = dir(fullfile(dirName,[pre{ii},'*.mat']));
curFiles = {curFiles.name}';
% Loop through all files with this prefix
for jj=1:numel(curFiles)
% Here the magic happens
end
end
Sorry, I misunderstood your question, I found this solution:
file = dir('*.mat')
matching = regexp({file.name}, '^[a-zA-Z_]+[0-9]+\.mat$', 'match', 'once'); %// Match once on file name, must be a series of A-Z a-z chars followed by numbers.
matching = matching(~cellfun('isempty', matching));
str = unique(regexp(matching, '^[a-zA-Z_]*', 'match', 'once'));
str = str(~cellfun('isempty', str));
group = cell(size(str));
for is = 1:length(str)
ismatch = strncmp(str{is}, matching, length(str{is}));
group{is} = matching(ismatch);
end
Answer came from this source: Matlab Central

Create a list and append file names to this list

I am trying to append filenames in a directory to a list for later processing. The code below does not work.
files = dir( fullfile(home,'*.csv') );
files = {files.name}'; %'# file names
symbolsList = [];
filedata = cell(numel(files),1); %# store file contents
for i=1:numel(files)
[pathstr,name,ext] = fileparts(files{i});
symbolsList(end + 1) = name; % THIS GIVES ERROR
end
In your code, symbolsList will be interpreted as an array of characters. The statement where the error is appearing is interpreted as appending a single character to symbolsList. You are probably getting a subscript alignment mismatch because a name will most likely have more than one character, yet you are trying to fit many characters into a single spot in that array of characters. That's probably not what you want.
You want each "space" to have a name. Because each name will most likely not have the same amount of characters, you should probably use a cell array instead:
files = dir( fullfile(home,'*.csv') );
files = {files.name}'; %'# file names
symbolsList = cell(numel(files),1); %// Change
filedata = cell(numel(files),1); %# store file contents
for i=1:numel(files)
[pathstr,name,ext] = fileparts(files{i});
symbolsList{i} = name; %// Change
end
Take note that I've pre-allocated the cell array and for each file you want to look at, I've indexed into the right cell and placed the name there. This is preferred over concatenation primarily due to efficiency. To access the ith name, simply do:
name_to_choose = symbolsList{i};
Minor Note
filedata in your code isn't being used anywhere at all. Are you sure you put all of your code up?

how to save a text file stored as a cell string of arrays after making changes to it?

I am a beginner in matlab scripting, i have a text file which i am editing(finding and deleting certain strings). after i do the necessary changes how do i save the file?
for example:
io_contents = 'testing.m';
filetext = fileread(io_contents);
expr = '[^\n]*.DataType [^\n]*';
fileread_info = regexp(filetext, expr, 'match');
C = textread('filetext', '%s', 'delimiter', '\n');
z=length(fileread_info);
if z>=1
C = C(cellfun(#isempty, strfind(C, 'auto')));
end
Every time i run this,it deletes the first match but doesnt save that in the testing.m file and continues iterating. should i open a new file,call testing.m inside it,makes the changes and then save it?thanks!
You are working in your local memory, what you need to do is to write your cell C into a file.
Assuming your cell is composed by strings you can do, for instance
C = {'aa', 'bb'} % // test
fid = fopen('out','w'); % // output file
cellfun(#(x)fprintf(fid,'%s\n',x),C) % // write strings to output file
fclose(fid) % // release resource
which gives
aa
bb
in the output file (out).

Converting comma to point

I have a text file like this column wise:
0,472412
0,455627
0,439148
0,421753
...
0,116577
0,086670
0,057373
0,027161
How can I convert the comma into dot in matlab?
This post on Matlabs site suggests:
function comma2point_overwrite( filespec )
% replaces all occurences of comma (",") with point (".") in a text-file.
% Note that the file is overwritten, which is the price for high speed.
file = memmapfile( filespec, 'writable', true );
comma = uint8(',');
point = uint8('.');
file.Data( transpose( file.Data==comma) ) = point;
delete(file)
end
... or you could do this:
wholefile = fileread('yourfile.txt') % read in entire file
newfiledata = strrep(wholefile,',','.') % replace commas with full stops
fileid = fopen('yourfile.txt','w') % open file to write
fprintf(fileid,'%s',newfiledata) % print to file
fclose(fid2)
Another option, (since you want to open the file into matlab's workspace) is to:
load the file using
a=load('filename.txt');
Because the comma is a default delimiter, you'll get a 2xN matrix, such as:
a =
0 472412
0 455627
0 439148
0 421753
Find the significant # of digits to get the proper decimal point position:
d = 10.^(1+floor(log10(abs(a(:,2)))));
then:
v=a(:,2)./d
will yield the vector you wanted. Now you can save it back to file, or do whatever...
a='0,00445'
a = 0,00445
b=strrep(a,',','.')
b = 0.00445