Help with appending onto a table in a loop

10 次查看(过去 30 天)
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 个评论
dpb
dpb 2022-8-31
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 2022-8-31
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

请先登录,再进行评论。

回答(1 个)

Image Analyst
Image Analyst 2022-8-26
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'});

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by