Take the 2-minute tour ×
clear all 
n=3;  % Three column

for ii=1:n
    C{ii}=cell(20,1) % Each column got 20 rows. 

for k=1:2

    for l=1:3

        for m=1:2

    X{j}='No strings attched';  % stored all generated data. 

   % I would like to know which column I should store the data. 
   %Randomly picking a column number 


    % Storing in that column. 

    ***C{r}='No strings attched';***




I've generated three columns and 20 rows. Within a nested loop, I generates a data and stored all of them. Next, I'm picking up a clum randomly and storing the data generated. However, I can see total number of generated data is 12. Which should in columns 1,2,1,3,1,*2,1*,2,3,1,2,1. Hence when I check C(1), it should show six data. But, I couldn't figure out how to do that. Any help appreciated.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

At the end, you're assigning a string to C{r}, which is a 20x1 cell. You then need to select a row from that 20x1 cell. For example, C{r}{1}.

Next, I'm not exactly sure what you're trying to do, but it sounds like, you want to have C{1}{1:6} to have data, but C{1}{7:20} should be empty. There are two ways to do this. The easiest way is actually to initialize the cells to cell(0, 1) and assign into C{r, end+1}, but this will be very slow if you have a lot of data. A better way is to stick with the cell(20, 1) initialization. You also need to add an array storing the actual length of the array (how many elements in the array are used) as opposed to the capacity (how many it can hold, which is 20). Or, instead of using an array, you could add it as the 2nd dimension of the C array. Your choice. Then your assignment would be utilize that count like so:

%Outside Loop
counts = zeros(1, n);

%Inside Loop
C{r}{counts(r) + 1} = blah blah
counts(r) = counts(r) + 1;

If you have more than 20 elements, you should double the capacity of the cell. Finally, to see the data stored in the first entry in C, you can use:

%After Loop

Note: I don't have access to Matlab at the moment so I'm not 100% sure it all parses correctly, but that's the main idea.

share|improve this answer

Your Answer


