Clear Filters
Clear Filters

Help with appending onto a table in a loop

10 views (last 30 days)
Hi All,
I have a bit of code where I am trying to create a table in a loop, appending on as each loop passes. No matter what way I try it, it only shows up with the last iteration, rather than the whole amount. Would anyone be able to help? Here is the code:
sqlTable = table;
sqlTableTemp = table;
% Doing for all non-adjusted
for i = 1:length(numModels)
sqlTableTemp.forecastType = repmat(forecastType,length(periodEnd),1);
sqlTableTemp.forecastName = repmat(forecastName,length(periodEnd),1);
sqlTableTemp.modelName = repmat(modelNames{i}, length(periodEnd),1);
sqlTableTemp.createDate = repmat(createDate,length(periodEnd),1);
sqlTableTemp.createTime = repmat(createTime,length(periodEnd),1);
sqlTableTemp.creator = repmat(creator,length(periodEnd),1);
sqlTableTemp.activeForecast = zeros(length(periodEnd),1);
sqlTableTemp.periodEnding = periodEnd;
sqlTableTemp.val = cell2mat(app.ForecastResultsTable.UserData(:,i+1));
sqlTable = [sqlTable;sqlTableTemp];
end
All comments and help would be appreciated.
Thanks, James
  6 Comments
dpb
dpb on 31 Aug 2022
The value of numModels over which you're looping is still undefined with the attached -- as are all the RH side variables given.
We can't even try to duplicate the example code but at least two have illustrated that the catenation would work as expected if the loop runs multiple times.
I'm with @Image Analyst, however, that it's probable the table can be built from the data directly instead, IF we could see what the starting data are instead...
James McBrearty
James McBrearty on 31 Aug 2022
So yeah, it was a bit of an error on my part. numModels was a number that was defined earlier in the source code. I forgot about this, and was trying for find the size of the original array. It was all fixed by changing the original for loop to be
for i=1:numModels
end
All of the code works fine now, and is 250 times faster for sql entry than the original code that was used.
Thanks for all the help everyone

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 26 Aug 2022
Why not just do
val = cell2mat(app.ForecastResultsTable.UserData(:,i+1)); % Or whatever.
sqlTable = table(forecastType(:), forecastName(:), modelNames(:), createDate(:), ...
createTime(:), creator(:), activeForecast(:), periodEnding(:), val(:),
'VariableNames', {'forecastType', 'forecastName', 'modelNames', 'createDate', ...
'createTime', 'creator', 'activeForecast', 'periodEnding', 'val'});

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!