How to save the output of a function in an array or cell?

3 views (last 30 days)
I have a function which is called from within a script. The function is in a between a for loop. So basically everytime the Function runs for one file then comes back to script and runs it again for another file. I get the output of function as
d = [23 78]
then for next file it would give me
d = [503 20]
There could also be
d = [234 439
783 48]
The columns are always 2 but the rows could be more than one. How can I have an array as:
final = [23 78
503 20
234 439
783 48]
Is there a way to populate an array with the function output? Thanks for your help is advance.

Answers (1)

Kye Taylor
Kye Taylor on 19 Oct 2012
I'm going to assume that the function which returns a matrix with r rows and 2 columns is named
returnTwo.m
Then use something like
nNewRows = 100;
maxRowsExpectedInOutput = 10; % guess the largest number of rows returned
d = zeros(nNewRows,2); % preallocate enough space for 100 rows initially
idx = 1; % the index where there is no data in d
for i = 1:numIt
tempOut = returnTwo(); % tempOut is r-by-2 matrix
d(idx:idx+size(tempOut,1) - 1,:) = tempOut;
idx = idx + size(tempOut,1); % increment idx appropriately
% check if d needs more rows added
if size(d,1)-idx <= maxRowsExpectedInOutput
d = [d;zeros(100,2)]; % add another 100 rows to d
end
end

Community Treasure Hunt

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

Start Hunting!