Search code examples
arraysmatlabloopsvariable-assignmentcell-array

Matlab array storing through loop


I have a for loop and each value a{i} b{i} c{i} is equal each time with a specific number. So I was wondering how can I put all those value in an array through loop. The way that I am using I mean this one [a{i};b{i};c{i}] it seems that it doesn't work! If I keep 2 out of three values is working but I want the data from all of the values (a b c)

You can see the (pseudo)code below:

for i=1:number of cells
   Cell{i}.Tri=[a{i};b{i};c{i}]
end

Solution

  • This can be done without a for loop by using cellfun combined with the cat function. EDIT: As noted in the comments, cellfun is itself a loop.

    % Create all variables
    a{1}=rand(10);
    a=repmat(a,10,1);
    b=a;
    c=a; 
    % Add a cell array of equal size to a. The contents of each cell are the dimension along which to concatenate. 
    catarg=num2cell(ones(size(a)))
    
    % Do the concatenation
    d=cellfun(@cat,catarg,a,b,c,'UniformOutput',false);