Matlab : Counting image in a folder using matlab GUI - matlab

I want to count the number of image in a folder using a GUI created in Matlab guide 2015b.
I have written this code:
Id = 3 (actually the value of id will be given by user at run time)
path =strcat ( ' c:\user\Desktop\New\TrainData\',Id)
path=strcat (path,'\')
d=dir (path)
n=length (d)
It shows the error that dir can not be used for cell input. This code is working when I use command prompt.
It shows error only when I want to use it through GUI. Initially I thought that it's a problem regarding the path.
So I displayed the path but it gave the perfect result.
I am confused. Kindly provide some solutions in Matlab

Instead of strcat you should use fullfile:
path = fullfile('c:\user\Desktop\New\TrainData',num2str(Id))
And be careful with dir, dir also list the subfolder so check that you only take into account the image file:
d = dir(path);
name = d(~[d.isdir]).name

Chances are you're getting your Id variable from a inputdlg or something. It is being read in as a cell array of strings rather than a string. You can check this using iscell:
iscell(Id)
% 1
You don't see any issues until you hit the dir command because strcat is able to handle this just fine but also yields a cell array of strings.
out = strcat('123', {'4'});
class(out)
% cell
If you read your error message thoroughly, the error explicitly states that the input to dir is a cell and not a string. The way to fix this is to first check if Id is a cell array and convert to a string if necessary.
Id = inputdlg('Enter an ID');
% Convert to a string if Id is a cell array
if iscell(Id)
Id = Id{1};
end
% Get a listing of all files/directories
d = dir(fullfile(folder, num2str(I)));
% Get number of files
nFiles = sum(~[d.isdir]);
Also, you don't want to try to concatenate a number with a string (strcat('abc', 1)) because this will convert the number to it's ASCII code. Instead you'll want to use num2str as shown above.

Related

Matlab saving a .mat file with a variable name

I am creating a matlab application that is analyzing data on a daily basis.
The data is read in from an csv file using xlsread()
[num, weather, raw]=xlsread('weather.xlsx');
% weather.xlsx is a spreadsheet that holds a list of other files (csv) i
% want to process
for i = 1:length(weather)
fn = [char(weather(i)) '.csv'];
% now read in the weather file, get data from the local weather files
fnOpen = xlsread(fn);
% now process the file to save out the .mat file with the location name
% for example, one file is dallasTX, so I would like that file to be
% saved as dallasTx.mat
% the next is denverCO, and so denverCO.mat, and so on.
% but if I try...
fnSave=[char(weather(i)) '.mat'] ;
save(fnSave, fnOpen) % this doesn't work
% I will be doing quite a bit of processing of the data in another
% application that will open each individual .mat file
end
++++++++++++++
Sorry about not providing the full information.
The error I get when I do the above is:
Error using save
Argument must contain a string.
And Xiangru and Wolfie, the save(fnSave, 'fnOpen') works as you suggested it would. Now I have a dallasTX.mat file, and the variable name inside is fnOpen. I can work with this now.
Thanks for the quick response.
It would be helpful if you provide the error message when it doesn't work.
For this case, I think the problem is the syntax for save. You will need to do:
save(fnSave, 'fnOpen'); % note the quotes
Also, you may use weather{i} instead of char(weather(i)).
From the documentation, when using the command
save(filename, variables)
variables should be as described:
Names of variables to save, specified as one or more character vectors or strings. When using the command form of save, you do not need to enclose the input in single or double quotes. variables can be in one of the following forms.
This means you should use
save(fnSave, 'fnOpen');
Since you want to also use a file name stored in a variable, command syntax isn't ideal as you'd have to use eval. In this case the alternative option would be
eval(['save ', fnSave, ' fnOpen']);
If you had a fixed file name (for future reference), this would be simpler
save C:/User/Docs/MyFile.mat fnOpen

Reading all the files in sequence in MATLAB

I am trying to read all the images in the folder in MATLAB using this code
flst=dir(str_Expfold);
But it shows me output like this. which is not the sequence as i want.
Can anyone please tell me how can i read all of them in sequence?
for giving downmark, please explain the reason for that too.
By alphabetical order depth10 comes before depth2. If at all possible, when creating string + num type filenames, use a fixed width numerical part (e.g. depth01, depth02) - this tends to avoid sorting problems.
If you are stuck with the filenames you have, and know the filename pattern, though, you can not bother using dir at all and create your filename list in the correct order in the first place:
for n = 1:50
fname = sprintf('depth%d.png',n);
% code to read and process images goes here
end
From the Matlab forums, the dir command output sorting is not specified, but it seems to be purely alphabetical order (with purely I mean that it does not take into account sorter filenames first). Therefore, you would have to manually sort the names. The following code is taken from this link (you probably want to change the file extension):
list = dir(fullfile(cd, '*.mat'));
name = {list.name};
str = sprintf('%s#', name{:});
num = sscanf(str, 'r_%d.mat#');
[dummy, index] = sort(num);
name = name(index);

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

How to use the obtained direction from "dir" to address the "dlmread" & "xlsread"

I want to read some "xlsx" & "txt" files from directory and process on that. Names of the files are the random word.
so I used a function(getAllFiles) to obtain all directions of those files which I founded in this link: How to get all files under a specific directory in MATLAB?.
when I want to use those direction in dlmread or xlsread it give an error as bellow:
??? Error using ==> dlmread at 55
Filename must be a string.
the code is as follow :
fileList = getAllFiles('/home/Network/econimi/SSS')
A=dlmread(fileList(2));
how can I convert fileList to the string format?
The output of getAllFiles is a cell array. As stated in the manual 'Cell array indices in smooth parentheses refer to sets of cells' which means fileList(2) is a cell as well. To access an element of a cell array, use curvy brackets.
Try:
A=dlmread(fileList{2});

Loading MATLAB .mat files in alphanumerical order

I'm currently attempting to load a number of MATLAB files which all contain the same variable in order to make a matrix of all the values.
These files all start with a number (i.e. 40_analysed.mat), which was previously extracted from different raw data files using regular expressions, meaning I have a vector composed of all the individual numbers (id).
When I try to load the values and display the data for all individuals in a single matrix using the code below, the files aren't loaded alphanumerically (i.e. according to id), instead appearing to be loaded randomly.
file = dir('*_analysed.mat');
for i=1:length(id);
load(file(i).name,'means');
overallThresholds{i} = means;
end
overallMeans = cell2mat(overallThresholds)
How could I do this so the resulting matrix would be in the correct order? Apologies if this question doesn't make much sense, the problem is a little hard to articulate!
If your filenames don't have a fixed-precision number (as #FakeDIY points out, that would mean they would already be sorted), you could do something like this:
file = dir('*_analysed.mat');
overalThresholds = cell(1, length(id));
IDs = zeros(1, length(id));
for i = 1:length(id)
fileName = file(i).name;
IDs(i) = str2double( strrep( fileName, '_analysed.mat', '' ) );
data = load(fileName, 'means');
overallThresholds{i} = data.means;
end
[~, reordering] = sort(IDs);
overallThresholds = overallThresholds(reordering);
In other words, store the file ID in a separate array as you're going along, and then reorder overallThresholds to be in sorted order of IDs using the second output of SORT.
(I also pre-allocated the arrays, and use the functional form of LOAD, but you don't really need to do that).
When one uses dir command, it is not promised that the results will be in alphabetical order. In fact, the manual says explicitly that:
dir lists the files and folders in the MATLAB current folder. Results
appear in the order returned by the operating system.
Even if you did get this in alphabetical order, nothing assures you that you will get it next time. Thus, you must order the results from dir using sort command.
[~,order] = sort( {file.name} );
file = file(order);