Karnivaurus
Karnivaurus

Reputation: 24161

Matlab: appending cell array

I have 10 binary files, each storing a list of numbers. I want to load each file in turn, and then append a cell array y with the numbers in that file. So if each file contains 20 numbers, I want my final cell to be 10x20. How do I do this? The following code does not work:

for i=1:10
    % Load an array into variable 'x'
    y = {y x}
end

Upvotes: 0

Views: 697

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112769

You only need a minor modification to your code:

y = cell(1,10); %// initiallize if possible. Not necessary
for ii = 1:10 %// better not use i as a variable (would override imaginary unit)
    %// Load an array into variable 'x'
    y{ii} = x; %// fill ii-th cell with x.
    %// Or use y{end+1} = x if you haven't initiallized y        
end

Upvotes: 2

bjornruffians
bjornruffians

Reputation: 701

If you are reading strictly numbers and want an array (rather than cells), this could work:

% read CSV numbers from file into array
temp = {};
out = [];
for i=1:10
   % my example files were called input1.txt, input2.txt, etc
   filename = strcat('input', num2str(i), '.txt');
   fid = fopen(filename, 'r');
   temp = textscan(fid,'%d','delimiter',',');      
   out(i,:) = cell2mat(temp);
   fclose(fid);
end

'out' is a 10x20 array

Upvotes: 1

Related Questions