How to get struct results in a loop?
4 views (last 30 days)
Show older comments
Marcio Schmidt
on 1 Feb 2021
Commented: Marcio Schmidt
on 1 Feb 2021
I have a function that reads a number of files with the extension .m and turns them into inline functions in a struct. The purpose of the function is that the user can load as many models as he wants and the program will always respond with the correct number of entries.
filePattern = fullfile(myFolder, 'model_*.m'); % Only files with prefix and suffix defined in this project
theFiles = dir(filePattern);
FnCarbona = struct; %Creates a structure that will receive function pointers in files
for k = 1 : length(theFiles) % This is from another post here in Matlab Answer
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Lendo o modelo .... %s\n', fullFileName);
newStr = regexprep(baseFileName,'.m','');
FnCarbona(k).ponteiro= str2func(newStr);
FnCarbona(k).nome = newStr;
end
[n, m]= size(FnCarbona);
This part works pretty well. If I run individually, I get the vectors correctly (5 vector 1x50 elements)
The problem is when I try to access this in a (for) loop.
data=zeros(m,50);
for i= 1: m
data(i)= FnCarbona(i).ponteiro();
end
Then I get the error message: Unable to perform assignment because the left and right sides have a different number of elements.
Could someone help me? I want
1 Comment
Stephen23
on 1 Feb 2021
Note that rather than creating an entirely new structure array FnCarbona (and expanding it on each loop iteration), you can simply use the already-existing theFiles structure array.
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!