how to store my result in a recursive function - matlab

i have a matlab function for listing all files in a folder, including its children folders. i can display them all , but i have no idea about how to store them in my output variable .
function out = searchfolder(varargin)
if nargin<1
helpdlg('no input floder');
return;
else
curfolder=varargin{1};
end
if ~isdir(curfolder) || length(dir(curfolder)) < 3
return;
end
children = dir(curfolder);
%eliminate '.' and '..'
children = children(3:end);
allfiles = {};
for i=1:length(children)
child = children(i);
thisone = fullfile(curfolder,child.name);
if child.isdir
searchfolder(thisone);
else
disp(thisone);
end
end
so how to figure out this problem?

with excaza's help , i have the code :
function out = searchfolder(varargin)
out = {};
if nargin<1
% helpdlg('no input floder');
return;
else
curfolder=varargin{1};
end
if ~isdir(curfolder) || length(dir(curfolder)) < 3
return;
end
children = dir(curfolder);
%eliminate '.' and '..'
children = children(3:end);
allfiles = {};
for i=1:length(children)
child = children(i);
thisone = fullfile(curfolder,child.name);
if child.isdir
out = [ out ;searchfolder(thisone)];
else
disp(thisone);
out = [out;{thisone}];
end
end

Related

How to generalize Matlab function?

I have a Matlab function. I need to generalize this function. This code’s aim is to check this IndicMPs are in the TableTemp, if it is there, then we extract relevant age limits, such as: Age_Limite_DC, Age_Limite_IT, Age_Limite_Ch and Transfert_Prime_IT_DC. My idea is to generalize, passing parameters to find out the "Type_pret" is.(May be I'm wrong) Since I'm beginner to Matlab can someone help me to encode a more generic function that can be used in a more general context?
function Structure = optimisation_function()
Data = load('Data.mat');
Structure = Data.Structure;
TableTemp = Data.TableTemp;
Age_Limite_DC = zeros(size(Structure,1),1);
Age_Limite_IT = zeros(size(Structure,1),1);
Age_Limite_CH = zeros(size(Structure,1),1);
Transfert_Prime_IT_DC = zeros(size(Structure,1),1);
for IndexMPAL = 1 : length(Structure.AnneeSouscription)
% Determine Type_Pret (Loan Type)
if ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'A'))
Type_Pret = 'A';
elseif ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'B'))
Type_Pret = 'B';
elseif ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'C'))
Type_Pret = 'C';
elseif ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'D'))
Type_Pret = 'D';
elseif ~isempty(strfind(Structure.Type_Pret{IndexMPAL},'E'))
Type_Pret = 'E';
end
MP_CP = Structure.NomCodeProduit(IndexMPAL);
MP_AnSous = Structure.AnneeSouscription(IndexMPAL);
MP_TypePret = Type_Pret;
IndicCP = strcmp(MP_CP, TableTemp.CodeProduit);
IndicAS = MP_AnSous== TableTemp.AnneeSouscription;
IndicTP = strcmp(MP_TypePret, TableTemp.TypePret);
IndicMP = IndicCP & IndicAS & IndicTP;
if ~any(IndicMP)
Msg = strcat('CodeProduct:',MP_CP{1}, ', Année Souscription:', num2str(MP_AnSous), ', Type Prêt:', MP_TypePret);
error('Error', Msg)
else
Age_Limite_DC(IndexMPAL,1) = TableTemp.Age_Limite_DC(IndicMP,1);
Age_Limite_IT(IndexMPAL,1) = TableTemp.Age_Limite_IT(IndicMP,1);
Age_Limite_CH(IndexMPAL,1) = TableTemp.Age_Limite_CH(IndicMP,1);
Transfert_Prime_IT_DC(IndexMPAL,1)=
TableTemp.Transfert_Prime_IT_DC(IndicMP,1);
end
end
Structure.Age_Limite_DC = Age_Limite_DC;
Structure.Age_Limite_IT = Age_Limite_IT;
Structure.Age_Limite_CH = Age_Limite_CH;
Structure.Transfert_Prime_IT_DC = Transfert_Prime_IT_DC;
end
The if/elseif can be simplified with a cell array:
liststr = {'A','BB','C','D','E'}; % builds a cell array, each cell contains a string
Positive_matches = strfind(liststr,Structure.Type_Pret{IndexMPAL}) % returns a list for each cell of the indices where the element was found (empty if none)
Index = find(~cellfun('isempty', Positive_matches )) % converts the previous list into a logical 0/1 array indicating whether an item was found (1) or not (0)
% if isempty(Index); continue; end % If no index is found, to avoid an error in the next instruction, skips the rest of the code.
Type_Pret = liststr(Index(1));
If the Type_Pret are the same in your list and in Structure? , you can usestrcmp`:
liststr = {'A','B','C','D','E'};
if any(strcmp(Structure.Type_Pret,liststr))
Type_Pret = Structure.Type_Pret
else
% handle error
end
You can also work directly on Structure.Age_Limite_DC without using Age_Limite_DC.

Why isnt this matlab code working?

I'm trying to write a script to remove comment lines from another script file. Here's what I tried:
fid = fopen('correct_answer.m');
aline = {};
counter = 1;
while ~feof(fid)
aline{counter} = fgetl(fid);
if aline{counter}(1) == '%'
aline{counter} = '';
end
counter = counter + 1;
end
This is the error I get:
Attempted to access aline.%cell(1); index out of bounds because numel(aline.%cell)=0.
Error in hw2 (line 8)
if aline{counter}(1) == '%'
If I run it without the while loop it works fine. What's up with this??
Also if you just happen to know a more simple/efficient approach to removing comment lines that would work too ;)
The problem is that you sometimes read empty lines, and you cannot access the first element of empty lines. Additionally you may have comments at the end of a valid line of code, this code should do the trick
fid = fopen('correct_answer.m');
aline = {};
counter = 1;
while ~feof(fid)
aline{counter} = fgetl(fid);
if ~isempty(aline{counter})
k = strfind(aline{counter}, '%');
aline{counter}(k:end) = '';
end
counter = counter + 1;
end

how I can read different text files in Matlab

How can I read different text files in Matlab.
Considering that there are 33 txt files and that every one should be processed.
Here is part of my code with the error.
textFilename = cell(1,33);
id = cell(1,33);
for k=1:33;
textFilename{k} = fullfile('C:\Users\Desktop\SentimentCode\textfiles',['file' num2str(k) '.txt']);
id{k} = fopen(textFilename{k},'rt');
str{k} = textscan(id{k},'%s%s');
str(str == '.') = '';
str(str == '_') = '';
str(str == '-') = '';
% Remove numbers from text
T =regexprep(str, '[\d]', ' ');
end
and my error is:
??? Undefined function or method 'eq' for input arguments of type 'cell'.
Error in ==> Untitled9 at 23
str(str == '.') = '';

Ini file read and write + add new property + matlab [duplicate]

This question already has an answer here:
Property_value + matlab
(1 answer)
Closed 9 years ago.
How to read and write ini files: I want to add new property to an existing one. I want to write the ini file to temp file and finally add the new property to it. the new property will have head,name,desc, value and layout (like: line 1 & 3)
#---------------
# head
# --------------
[name]% type
# desc
value
fileData = [];
fh = fopen( fileName, 'r' ); % read handle
tname=tempname();
wfh =fopen(tname,'w'); % write handle
line = fgetl(fh);
val = '';
Prop ='';
type = '';
header = '';
desc= '';
while ischar(line)
if strcmpi(line(1),'#') && strcmpi(line(3),'=')
layout = line(2:end);
elseif strcmpi(line(1),'#')&& ~strcmpi(line(3),'=')
header = line(2:end);
else
Prop = regexp(line,{'\[*\w+\]\s*%\s*.*\s*'},'match');
[property data_type] = strtok(Prop,'%')
prop_p = property{1};% property_name
prop_per = regexprep(prop_p,{'\[','\]'},'');
prop = prop_per{1};
Dtype = data_type{1}; % datatype
dtype = strtrim(strrep(Dtype,'%',''));
DATA_type = dtype{1};
end
% How can i define filedname (prop) for the 'layout' and 'header' as they are found in lines before the actual'prop'.
% From command window
% Undefined variable prop.
% Error in ecco2511>add (line 212)
% fileData.(prop{1}).layout = layout;
desc = fgetl(fh); % description
desc = desc(1:end);
line = fgetl(fh);
val = line(1:end);
fileData.(prop).layout = layout;
fileData.(prop).header = header;
fileData.(prop).type = DATA_type;
fileData.(prop).desc = desc;
fileData.(prop).val = val;
line = fgetl(fh); % keep reading
end
if ~isfield( fileData, propName)
fileData.(propName).val = newVal;
fileData.(propName).type = datatype;
fileData.(propName).desc = description;
fileData.(propName).layout = layout;
fileData.(propName).header = header;
else
error ( 'property %s already exists, use set to change its value',propName );
end
fileData = orderfields( fileData );
propNames = fieldnames( fileData );
for ii = 1:numel( propNames )
fprintf(wfh,'%s\r',fileData.(propNames{ii}).layout);
fprintf(wfh,'\n');
fprintf(wfh,'%s\r',fileData.(propNames{ii}).header);
fprintf(wfh,'\n');
fprintf(wfh,'%s\r',fileData.(propNames{ii}).layout);
fprintf(wfh,'\n');
fprintf( wfh, '[%s]%s\r', (propNames{ii}),fileData.(propNames{ii}).type);
fprintf(wfh,'\n');
fprintf( wfh,'#%s\r',fileData.(propNames{ii}).desc);
fprintf(wfh,'\n');
fprintf( wfh,'%s\r',fileData.(propNames{ii}).val);
fprintf(wfh,'\n');
end
fclose(fh);
fclose(wfh);
[status,errmsg]= movefile(tname,fileName,'f');
Sounds like you need INI Config from MATLAB File Exchange. It will allow you to read, write, and modify INI style files. I have used it a number of times and it works quite well.

unexpected results of a function in matlab

Normally this function should give me the values ​​1, 2, 3 or 4. but when I use it, I get 0, 1 or 2. Could you help me to know where is the problem:
function Vecteur_retour = var_Test(Test)
AA = Test;
var_Test = zeros(1,2000);
for i=3:1:2000
if AA(i)<=AA(i-1) && AA(i-1)<=AA(i-2)
var_Test(i)=1;
else
if AA(i)<=AA(i-1) && AA(i-1)>AA(i-2)
var_Test(i)=2;
if AA(i)>AA(i-1) && AA(i-1)<=AA(i-2)
var_Test(i)=3;
else
if AA(i)>AA(i-1) && AA(i-1)>AA(i-2)
var_Test(i)=4;
end
end
end
end
end
Vecteur_retour = var_Test;
Vector comparisons will be much faster:
var_Test = ones(1,2000);
delta_Test = diff(Test);
var_Test([0 0 delta_Test(1:end-1)] > 0) = 2;
var_Test([0 delta_Test] > 0) = var_Test([0 delta_Test] > 0) + 2;
var_Test(1:2) = 0;
Probably because you never reach the cases var_Test(i) = 3 or var_Test(i) = 4.
You have a problem with your if and end blocks. The way you have it, case 3 is only reached if case 2 is hit first, but these are contradictory.
You want code more like.
function Vecteur_retour = var_Test(Test)
AA = Test;
var_Test = zeros(1,2000);
for i=3:1:2000
if AA(i)<=AA(i-1) && AA(i-1)<=AA(i-2)
var_Test(i)=1;
else
if AA(i)<=AA(i-1) && AA(i-1)>AA(i-2)
var_Test(i)=2;
else % you forgot this else
if AA(i)>AA(i-1) && AA(i-1)<=AA(i-2)
var_Test(i)=3;
else
if AA(i)>AA(i-1) && AA(i-1)>AA(i-2)
var_Test(i)=4;
end
end
end
end
end
Vecteur_retour = var_Test;
Careful indentation would have helped here.