How can I create a table with no specific number of rows and input various data types row by row?

7 views (last 30 days)

I need to store data out of a database into a table/matrix. Currently I'm using the following solution, so far so good. But there are also data types like strings (Names etc) in other words I need another way to store that data. I found the table function but don't know how to use in my case.

Here how it currently works:

objresult.Open(); %COM Objects, not relevant
objresult.MoveFirst();
row = 0;
result = [];
while row < objresult.CountRows
        result(row+1,1) = objresult.Item('F_State'); 
        result(row+1,2) = double(objresult.Item('Result_ID'));
        ....
        objresult.MoveNext(); %COM Object
        row = row + 1;    
end

Thanks in advance!

Accepted Answer

Peter Perkins
Peter Perkins on 20 Apr 2018
Edited: Peter Perkins on 20 Apr 2018

I'm only guessing at what you mean by "no specific number of rows". "objresult.CountRows" looks like it know how many there are, but I actually don't know how those things work. Your while loop suggests that you need to check for more rows each time you read one.

In R2018a, you can do something like this:

t = table('Size',[0 2],'VariableTypes',{'string' 'double'},'VariableNames',{'F_State' 'ResultID'});
while row < objresult.CountRows
    t.F_State(row) = objresult.Item('F_State'); 
    t.ResultID(row) = double(objresult.Item('Result_ID'))
    ...
end

Prior to R2018a, only thing that needs to change is the call to table, just preallocate double and string column vectors. But the performance of that is not going to be great, because it's going to be growing the table at each iteration. Best if you know how many in advance, or if you grow it in chunks rather than one row at a time.

More Answers (1)

s.h.m_89
s.h.m_89 on 22 Apr 2018
Edited: s.h.m_89 on 22 Apr 2018
Thank you for your help. I had a solution that is very close to yours and as you mentioned the performance is not the best.
You are right 'objresult.CountRows' counts the rows of the database table. My fault, I will use it as you recommended.
Many thanks again, best

Categories

Find more on Tables in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!