How to get image files from subdirectories within a directory - matlab

In matlab i want to access all the images of the extension ".hdr" from subdirectories which in turn are in a directory. And consequently all the image-names must be returned in a cell with one row and many columns, depending upon the number of images.I already used 'getAllFile' but I couldn't get the desired results. Please help me with any other idea. Thank you :-)

Depending on the context, you have a few options. If this program is interacting with a user try this:
[filelist path] = uigetfile('.hdr', 'MultiSelect', 'on')
for ii =1:numel(filelist)
filedir = fullfile(path, filelist{ii};
% Do whatever you want with each file here.
end
In the case above, filelist is the cell array you mentioned in your question. If this isn't what you need, let me know, and I'll add another option.

Related

How to perform processinng on .csv files used by my code for each person in one go without defining functions for each person in Matlab?

I have a main code named as process.m in which I define the path to 4 different .csv files for calculating values for each person. If I have a list of 30 persons and I don't want to define process.m as a function for each person, how can I do the processing for all the persons in one go. I want some idea by which process.m itself picks files for one person, then generate the results, then move to other person, pick his .csv files, generate the result and so on.
A breif outline of my code is attached here that would project the problem.
file1='Joseph_front.csv';
file2='Joseph_side.csv';
file3='Joseph_knee.csv';
file4='Joseph_back.csv';
A1=initiate2(file1); %initiate2 function reads the csv and perfoms some filtering operations on image in .csv format
A2=initiate2(file2);
A3=initiate2(file3);
A4=initiate2(file4);
%%omitted large part of code
cal(1) = p+q+r*s;
cal(2) = p+q+r+s;
cal(3) = p+q+r-s;
cal=cal'
%code to write the calculation in excel file
excelfile= 'test.xlsx';
xlswrite(excelfile,ValuesInInches,'Joseph_data',posColumn);
Describing more i want my code to process for 30 people all at once by selecting and picking the files itself, although i have done this operation by making the same code as a function for each person, but that is not very efficient as when I have to make a small change I have to make it in every function that means one change needs to be edited in 30 functions. Please suggest an efficient way to do it.
Note: All persons .csv files are named in the same manner and exist in the current folder.
I am assuming all of your files in one directory and there's no other files .
This portion of code will get the available filenames.
listFiles = dir('path of the directory');
filenames = strings; % an empty string array to save the filenames
j = 1;
for i = 1:1:length(listFiles)
if ~listFiles(i).isdir % to avoid the directory names
filenames(j,1) = listFiles(i).name;
j = j+1;
end
end
Now, there's 4 file for each person. So the loop should take 4 files at a time.
for ii = 1:4:length(filenames)
file1=filename(i);
file2=filename(i+1);
file3=filename(i+2);
file4=filename(i+3);
%% continue with your code
end

randomly move files from a folder to another folder?

I am trying to move my files and create a new folder to put those files there.
I have many .png files in my images folder in my MATLAB directory. I want to randomly choose 80% of them and move them to another folder called training folder in my matlab directory. Heres my code which is not working. it cant find the file to move :(
data_add = fullfile(cd,'images');
all_files = dir(data_add);
all_files = all_files(3:end);
num_files = numel(all_files);
image_order = randperm(num_files);
for k = 1:(image_order)*0.8
file_name = all_files(k).name;
file_add = all_files(k).folder;
file_to_move = fullfile('path_to_images\images',file_name);
mkdir training
movefile file_to_move training
end
A couple issues here:
Like Flynn comments, the call to mkdir training only needs to be made once, so you can place it before your loop.
You may be thinking about the variable image_order incorrectly when it comes to your for loop.
The call image_order = randperm(num_files); produces an array of randomly ordered indices from 1:num_files, which is helpful. However, the expression (image_order)*0.8 is actually multiplying each of these indices times 0.8, such that they are no longer valid, integer indices (aside from a few, like 8 which would become 1).
I think what you are attempting and wanting to do is this:
mkdir('training');
for k = 1:num_files*0.8
randK = image_order(k);
file_name = all_files(randK).name;
file_to_move = fullfile(data_add,file_name);
movefile(file_to_move, 'training'); % using function style
end
You may run into other issues next depending on where the folder training is located and where you are running your script from, but this should be closer to what you are to get, and at least locate the files for you.

Auto generate a name when saving file in Matlab?

I am working on a GUI and I have a file named 'work.mid'. The user can make some modifications to it and when they click the save button I want it to be saved as 'work1.mid' to 'c:\saved_datas\'. When they click that button second time, it should save it as 'work2.mid', on the third time 'work3.mid' and so on. Here's the code I have so far:
nmat = readmidi_java('work.mid');
Name = fullfile('c:\saved_datas\', '?????');
writemidi_java(nmat, Name);
Figuring out what should go at ????? is where I'm stuck.
The following code would work if you have no prior work*.mid or if you have any number of sequential work*.mid files inside c:\saved_datas\. Now, if the files are not in sequence, this code could be tweaked for that, just let me know if you would like to handle that case too.
Code listed here -
%// Parameters
org_filename = 'work.mid';
main_dir = 'c:\saved_datas\'; %//'
%// Your code
nmat = readmidi_java(org_filename);
%// Added code
[~,filename_noext,ext] = fileparts(org_filename)
filenames = ls(strcat(main_dir,filename_noext,'*',ext))
new_filename = strcat(filename_noext,num2str(size(filenames,1)+1),ext)
Name = fullfile(main_dir,new_filename)
%// Your code
writemidi_java(nmat, Name);
For achieving uniqueness of filenames, some also use timestamps. This could be implemented like this -
org_filename = 'work.mid'; %//'
main_dir = 'c:\saved_datas\'; %//'
[~,filename_noext,ext] = fileparts(org_filename)
new_filename = strcat('filename_noext','-',datestr(clock,'yyyy-mm-dd-hh-MM-SS'),ext)
Name = fullfile(main_dir,new_filename);
This could be done a couple of ways depending on how you have structured your GUI. You need to keep track of how many times the button has been pressed. In the callback for the button you could use a persistent variable ('count') and increment it by one at the start of the function. Then construct the filename with filename = ['work' num2str(count) '.mid']. Alternatively you could increment a class member variable if you have implemented your GUI using OOP.
To save the file use the 'save()' function with the previously constructed file name and a reference to the variable.
Check out the documentation for persistent variables, save, fullfile and uiputfile for extra info.

Removing 'AllFiles' from file types when using uigetfile

I'm using uigetfile with a custom set of FilterSpecs. Here is the sentence:
[FileName,PathName,FilterIndex] = uigetfile({'*.wav';'*.mp3'},'Open Audio File');
As you can see my FilterSpec is {'*.wav';'*.mp3'} and this works perfectly fine. My problem is simple, is just that matlab is always appending AllFiles(*.*) to my FilterSpecs. I have searched in Matlab docs and it literally states:
"uigetfile appends All Files(.) to the file types when FilterSpec is a string.", but the problem is that I don't see another way of specifying a custom FilterSpec without using strings.Sorry if this results in a dumb question.
Thanks in advance
There's no way to (easily) remove the 'AllFiles' from uigetfile() since it's always added by MATLAB.
If you really want to do it, you have to copy the uigetputfile_helper() code (to
MYuigetputfile_helper() for example) and change it. And then you call it from your MYuigetfile() - same idea here.
The change would be around lines 311 and 319 in my version from uigetputfile_helper(), i.e.
% Now add 'All Files' appropriately.
if (addAllFiles)
% If a string, create a cell array and append '*.*'.
if (~iscell(returned_filter))
returned_filter = {returned_filter; '*.*'};
% If it is a cell array without descriptors, add '*.*'.
elseif (size(returned_filter, 2) == 1)
returned_filter{end+1} = '*.*';
end
end
Hope that helps... have fun!
If you back up a few lines from the previous poster's answer, you'll see a comment:
We want to add 'All Files' in all cases unless we have a cell array with descriptors.
This comment is on line 245 of uigetputfile_helper for me. Simply describe your file types at the time you call uigetfile, and you won't see All Files (*.*)
Example:
[fname,pname] = uigetfile({'*.m','MATLAB Code (*.m)';'*.mat','MATLAB Data (*.mat)'});

Call graph generation from matlab src code

I am trying to create a function call graph for around 500 matlab src files. I am unable to find any tools which could help me do the same for multiple src files.
Is anyone familiar with any tools or plugins?
In case any such tools are not available, any suggestions on reading 6000 lines of matlab code
without documentation is welcome.
Let me suggest M2HTML, a tool to automatically generate HTML documentation of your MATLAB m-files. Among its feature list:
Finds dependencies between functions and generates a dependency graph (using the dot tool of GraphViz)
Automatic cross-referencing of functions and subfunctions with their definition in the source code
Check out this demo page to see an example of the output of this tool.
I recommend looking into using the depfun function to construct a call graph. See http://www.mathworks.com/help/techdoc/ref/depfun.html for more information.
In particular, I've found that calling depfun with the '-toponly' argument, then iterating over the results, is an excellent way to construct a call graph by hand. Unfortunately, I no longer have access to any of the code that I've written using this.
I take it you mean you want to see exactly how your code is running - what functions call what subfunctions, when, and how long those run for?
Take a look at the MATLAB Code Profiler. Execute your code as follows:
>> profile on -history; MyCode; profile viewer
>> p = profile('info');
p contains the function history, From that same help page I linked above:
The history data describes the sequence of functions entered and exited during execution. The profile command returns history data in the FunctionHistory field of the structure it returns. The history data is a 2-by-n array. The first row contains Boolean values, where 0 means entrance into a function and 1 means exit from a function. The second row identifies the function being entered or exited by its index in the FunctionTable field. This example [below] reads the history data and displays it in the MATLAB Command Window.
profile on -history
plot(magic(4));
p = profile('info');
for n = 1:size(p.FunctionHistory,2)
if p.FunctionHistory(1,n)==0
str = 'entering function: ';
else
str = 'exiting function: ';
end
disp([str p.FunctionTable(p.FunctionHistory(2,n)).FunctionName])
end
You don't necessarily need to display the entrance and exit calls like the above example; just looking at p.FunctionTable and p.FunctionHistory will suffice to show when code enters and exits functions.
There are already a lot of answers to this question.
However, because I liked the question, and I love to procrastinate, here is my take at answering this (It is close to the approach presented by Dang Khoa, but different enough to be posted, in my opinion):
The idea is to run the profile function, along with a digraph to represent the data.
profile on
Main % Code to be analized
p = profile('info');
Now p is a structure. In particular, it contains the field FunctionTable, which is a structure array, where each structure contains information about one of the calls during the execution of Main.m. To keep only the functions, we will have to check, for each element in FunctionTable, if it is a function, i.e. if p.FunctionTable(ii).Type is 'M-function'
In order to represent the information, let's use a MATLAB's digraph object:
N = numel(p.FunctionTable);
G = digraph;
G = addnode(G,N);
nlabels = {};
for ii = 1:N
Children = p.FunctionTable(ii).Children;
if ~isempty(Children)
for jj = 1:numel(Children)
G = addedge(G,ii,Children(jj).Index);
end
end
end
Count = 1;
for ii=1:N
if ~strcmp(p.FunctionTable(ii).Type,'M-function') % Keep only the functions
G = rmnode(G,Count);
else
Nchars = min(length(p.FunctionTable(ii).FunctionName),10);
nlabels{Count} = p.FunctionTable(ii).FunctionName(1:Nchars);
Count = Count + 1;
end
end
plot(G,'NodeLabel',nlabels,'layout','layered')
G is a directed graph, where node #i refers to the i-th element in the structure array p.FunctionTable where an edge connects node #i to node #j if the function represented by node #i is a parent to the one represented by node #j.
The plot is pretty ugly when applied to my big program but it might be nicer for smaller functions:
Zooming in on a subpart of the graph:
I agree with the m2html answer, I just wanted to say the following the example from the m2html/mdot documentation is good:
mdot('m2html.mat','m2html.dot');
!dot -Tps m2html.dot -o m2html.ps
!neato -Tps m2html.dot -o m2html.ps
But I had better luck with exporting to pdf:
mdot('m2html.mat','m2html.dot');
!dot -Tpdf m2html.dot -o m2html.pdf
Also, before you try the above commands you must issue something like the following:
m2html('mfiles','..\some\dir\with\code\','htmldir','doc_dir','graph','on')
I found the m2html very helpful (in combination with the Graphviz software). However, in my case I wanted to create documentation of a program included in a folder but ignoring some subfolders and .m files. I found that, by adding to the m2html call the "ignoreddir" flag, one can make the program ignore some subfolders. However, I didn't find an analogue flag for ignoring .m files (neither does the "ignoreddir" flag do the job). As a workaround, adding the following line after line 1306 in the m2html.m file allows for using the "ignoreddir" flag for ignoring .m files as well:
d = {d{~ismember(d,{ignoredDir{:}})}};
So, for instance, for generating html documentation of a program included in folder "program_folder" but ignoring "subfolder_1" subfolder and "test.m" file, one should execute something like this:
m2html( 'mfiles', 'program_folder', ... % set program folder
'save', 'on', ... % provide the m2html.mat
'htmldir', './doc', ... % set doc folder
'graph', 'on', ... % produce the graph.dot file to be used for the visualization, for example, as a flux/block diagram
'recursive', 'on', ... % consider also all the subfolders inside the program folders
'global', 'on', ... % link also calls between functions in different folders, i.e., do not link only the calls for the functions which are in the same folder
'ignoreddir', { 'subfolder_1' 'test.m' } ); % ignore the following folders/files
Please note that all subfolders with name "subfolder_1" and all files with name "test.m" inside the "program_folder" will be ignored.