开发者

Cell array within nested loop

clc 
clear all 
n=3;  % Three column
j=1;


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

for 开发者_开发百科k=1:2

    for l=1:3

        for m=1:2


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


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

    r=ceil(rand(1,1)*n)   

    % Storing in that column. 

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

        end 

    end 

end

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.


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
C{1}{1:counts(1)}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜