1

I have a 69x1cell array. Each row contains 3 columns of double but with variable numbers of rows.

In each row there are, for example;

4x3 double 13x3 double ... etc.

I extract all the data from the cell array into one matrix using;

result = vertcat(data{:})

What I would like to do is to give them an identify based on which cell they are extracted from in the data cell array. For example, the 4 rows extracted from the 1st row in the data cell array would have 1 in front of them...so i would get something like;

1,x,y,z
1,x,y,z
1,x,y,z
1,x,y,z (as row 1 in data has 4 rows)
2,x,y,z
2,x,y,z (for the 13 rows)

1 Answer 1

2

This is one way:

data = { rand(2,3);
         rand(5,3) }

%// create identity vector
out1 = cell2mat(arrayfun(@(x) x.*ones(1,size(data{x},1)), 1:numel(data),'uni',0)).' %'
%// convert data from cell to double matrix
out2 = cell2mat(data)

%// concatenate output
out = [ out1 , out2 ]

or directly

out = cell2mat([arrayfun(@(x)x.*ones(1,size(data{x},1)).',1:numel(data),'uni',0).',data])

or a little more fancy and a bit less costly (untested):

%// create identity vector
A(cumsum([1; cellfun(@(x) size(x,1),data)])) = 1

%// concatenate output
out = [cumsum(A(1:end-1)).' cell2mat(data)]

gives:

data = 
    [2x3 double]
    [5x3 double]


out =
            1      0.88441     0.018613      0.43851
            1      0.72086      0.67478      0.43782
            2      0.11704      0.37569      0.51537
            2      0.81468      0.54655      0.65753
            2      0.32486      0.56192      0.95092
            2      0.24623      0.39582      0.72235
            2      0.34271      0.39813      0.40008
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! @thewatwewalk I just tested your "untested" method, and it works perfectly too.
@user3644826 the "untested" comment was regarding the "a bit less costly" statement :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.