0

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 

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, yes that works fine if I know how many files there are, but what if I don't? How can I continuously append an element to the cell array? (I know that there are simple ways to find out the number of files, but I'm more interested in the method for dynamic cell allocation.)
Just remove first line. Initiallization is not necessary; it is just recommended to speed up code
Ah, thanks. Finally, suppose this is not in a loop and at some point I want to append a cell element to the end of the cell array, without having the index, how can I do that?
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.