Help preallocating variables for a table
이전 댓글 표시
Hi everyone,
so i have written some code which goes like this:
function caTable = makeCaTable(caCM)
% creates a table with information about the frames(coordinates of the
% centroids and the total number of cells in the frame)
Frame = {};
PosX = {};
PosY = {};
NumberOfCells = {};
for i = 1:size(caCM,2)
C = chop(caCM{1,i},0);
for j = 1:size(C,1)
Frame{end+1,1} = i;
PosX{end+1,1} = C(j,1);
PosY{end+1,1} = C(j,2);
if(j == 1)
NumberOfCells{end+1,1} = size(C,1);
else
NumberOfCells{end+1,1} = '-';
end
end
end
% write the table
caTable = table(Frame, PosX, PosY, NumberOfCells);
it works and gives me the results i want. But now i want to preallocate the variables. I thought I do it like this:
[nrows,ncols] = cellfun(@size,caCM);
rows = sum(nrows);
Frames = cell(rows,1);
PosX = cell(rows,1);
PosY = cell(rows,1);
NumberOfObjects = cell(rows,1);
But if i do so i cant use my for loop the way i wrote it, since it would always put the values at the end of the preallocated matrices. But if i simply use:
Frames(j,1) = i
my table will not have all the fields. I really don't know how i can fix this. Maybe some of you could help me with that.
Thank you very much!
댓글 수: 2
Please get rid of all the extra blank lines you've added to the code and in the future use the {}Code button to format code as such, as I've done for you now.
What is C (returned by chop)? A cell array? A matrix?
Why are PosX, PosY and particularly Frame cell arrays. Frame only stores scalar numerics. Not sure about PosX and PosY (depends on what C is).
Julian
2018년 9월 13일
채택된 답변
추가 답변 (1개)
Steven Lord
2018년 9월 13일
0 개 추천
I think you want to use the T = table('Size',sz,'VariableTypes',varTypes) syntax shown on the documentation page for the table function.
댓글 수: 2
Peter Perkins
2018년 9월 13일
The preallocation syntax that Steve is referring to was introduced in R2018a.
But Guillaume's answer avoids needing to preallocate the table, because nothing is growing dynamically, and everything is a vectorized assignment. +1.
카테고리
도움말 센터 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!