Thijser
Thijser

Reputation: 2633

Matlab store matrix in cell

I have a function that returns a matrix of information that I want to store in a cell, however no matter how I try this it keeps giving me various errors or the results are incorrect, my latest attempt is shown below:

bbag=[]
for j=3:100
    bag=rand(randi([1 5]),randi([1 5]))%stand in for more complex function that normally returns between 1 and 4 
    [dontcare,y] = size(bag);
    tbag={bag(1,1),bag(2,1),bag(3,1),bag(4,1),bag(4,1)}
    for i=2:y
        tbag=[tbag,{bag(1,i),bag(2,i),bag(3,i),bag(4,i)}]; %some kind of loop is probably required here 
    end
    bbag=vertcat(bbag,tbag)
    labels(i) = 1;
end

but this cannot handle when the data contains anything other than 4 data columns and if it does it only manages to append all the data on the same row not put it in it's own cell, any idea how to do this such that by the end I can ask for bbag(2,3) and then return a cell containing between 1 and 5 values? If I fix the sizes to be 4 then I instead get a 98-by-17 cell block (rather then 98x4x4 that I would expect). Any ideas?

Upvotes: 0

Views: 244

Answers (1)

user2271770
user2271770

Reputation:

In

bag=rand(randi([1 5]),randi([1 5]));

you create a random matrix with random size (i.e. random number of rows and columns). I don't know if the errors have anything to do with cell array creation; they have everything to do with the fact that you access e.g. row 3 from bag without making sure that you actually have 3 rows in it.

Also, check the doc for mat2cell for splitting a matrix into a cell array of heterogeneous-size matrices (if this is indeed what you're looking for).

Upvotes: 2

Related Questions